二维码生成
from PIL import Image
import qrcode
from qrcode.image.styledpil import StyledPilImage
from qrcode.image.styles.colormasks import SolidFillColorMask
from qrcode.image.styles.moduledrawers import SquareModuleDrawer
# 创建二维码对象
qr = qrcode.QRCode(
version=7,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=4,
)
# 添加数据
data = "https://www.baidu.com"
qr.add_data(data)
qr.make(fit=True)
# 生成带嵌入图像的二维码
# img = qr.make_image(
# image_factory=StyledPilImage,
# module_drawer=SquareModuleDrawer(),
# color_mask=SolidFillColorMask(back_color=(255, 255, 255), front_color=(0, 0, 0)),
# embeded_image_path="1.jpg" # 嵌入图像的路径
# )
img = qr.make_image(fill_color=( 213 , 143 , 1 ), back_color="lightblue")
# 保存图像
img.save("qrcode.png")
二维码识别
import cv2
from pyzbar.pyzbar import decode
# 读取图像
image = cv2.imread('qrcode.png')
# 转换为灰度图像
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 使用 Pyzbar 进行二维码解码
decoded_objects = decode(gray_image)
# 打印识别的结果
if not decoded_objects:
print("未能识别二维码")
else:
for obj in decoded_objects:
print('Type:', obj.type)
print('Data:', obj.data.decode('utf-8'))