使用python玩转二维码!速学速用!⛵

使用python玩转二维码!速学速用!⛵

💡 作者:韩信子@ShowMeAI
📘 Python3◉技能提升系列https://www.showmeai.tech/tutorials/56
📘 本文地址https://showmeai.tech/article-detail/398
📢 声明:版权所有,转载请联系平台与作者并注明出处
📢 收藏ShowMeAI查看更多精彩内容

使用python玩转二维码!速学速用!⛵

二维码用某种特定的几何图形来记录数据符号信息,这些黑白相间的图形按照一定的规律分布在平面上(二维方向)。二维码是目前最常使用的快捷信息存储方式之一,微信等都可以通过这项技术实现快扫快用。

在本篇内容中,ShowMeAI带大家来学习二维码的应用技能,包括构建二维码解码二维码

💡 二维码历史

QR(Quick Response,快速响应)Code 诞生于 1994 年的日本汽车公司 Denso Wave,是一种二维条形码,由在白色背景上排列成方形网格的黑色方块组成,允许立即访问隐藏在代码中的信息。

使用python玩转二维码!速学速用!⛵

QR码(也就是我们常说的二维码)可存储 7000 多个字符,由相机等设备读取,并从像素图像中解析出包含的信息,读取速度比其他条码快得多。

💡 二维码应用场景

生成和读取二维码的简便性导致它们在零售店、银行、医院、旅游和食品服务行业的产品包装、非接触式商务、订单处理、结帐和支付服务中得到广泛采用。我们常用到通信软件、社交平台都几乎都可以通过二维码来扫码识别。

2020 年 9 月对美国和英国消费者进行的一项调查发现,在COVID-19大流行期间二维码的使用有所增加。

使用python玩转二维码!速学速用!⛵

💡 生成二维码

我们先安装和导入本次需要用到的 Python 工具库qrcode,它可以很方便地创建和读取二维码。

import qrcode 

创建数据。

data="https://www.showmeai.tech" 

创建二维码实例。

qr= qrcode.QRCode(version=1, box_size=10, border=4, error_correction=qrcode.constants.ERROR_CORRECT_H) 
使用python玩转二维码!速学速用!⛵

我们对参数做一个解释:

qr.add_data(data) qr.make(fit=True) 

最后,使用生成二维码make_image()将 QRCode 对象转换为图像文件并保存在文件中。

qr_img=qr.make_image(fill_color="black", back_color="white") qr_img.save("qr.jpg") 

其中,fill_colorback_color可以改变二维码的背景和绘画颜色。

💡 阅读二维码

本篇我们将讲解两种不同的方式来读取二维码,使用cv2pyzbar

💦 opencv 读取解码

导入库。

import cv2 

打开上方存储的qr.jpg图像文件。

cv_img= cv2.imread("qr.jpg") 

在 CV2 中创建类 QRCodeDetector 的对象。

qr_detect= cv2.QRCodeDetector() data, bbox, st_qrcode= qr_detect.detectAndDecode(cv_img) 

detectAndDecode()检测并解码图像中存在的二维码。该方法返回以下内容:

print(f"QRCode data:n{data}") 
使用python玩转二维码!速学速用!⛵

💦 pyzbar 读取解码

使用 cv2 读取图像。

import cv2 from pyzbar.pyzbar import decode # read the image using cv2 img = cv2.imread("qr.jpg") 

接下来,找到图像中的条形码和二维码。

# Decode the barcode and QR Code in the image detectedBarcodes = decode(img) 

decode会遍历图像中所有检测到的条形码。返回结果数组的每个元素代表一个检测到的条形码,可以读取图像中的多个条形码或 QR 码。

每个检测到的条码包含以下信息:

# read the image in numpy array using cv2 img = cv2.imread("qr.jpg")# Decode the barcode image detectedBarcodes = decode(img)# If barcode is not detected then print the message if not detectedBarcodes:     print("Bar code not detected or your barcode is blank or corrupted!") else:# Iterate through all the detected barcodes in image     for bar_code in detectedBarcodes:# Locate the barcode position in image using rect         (x, y, w, h) = bar_code.rect# Highlight the rectanngela round the bar code         cv2.rectangle(img, (x-10, y-10),                       (x + w+10, y + h+10),                       (255, 0, 0), 2)if bar_code.data!="":# Print the barcode data             print(f"Data :  {bar_code.data.decode('UTF-8')}")             print(f"Bar Code Type: {bar_code.type}")             print(f"Bar Code Orientation: {bar_code.orientation}") 
使用python玩转二维码!速学速用!⛵

参考资料

推荐阅读

使用python玩转二维码!速学速用!⛵

举报
发表评论

评论已关闭。

相关文章

当前内容话题
  • 0