本文目录导读:

我来分享几个Python识别二维码的实用案例:
使用pyzbar库(推荐)
安装
pip install pyzbar pillow opencv-python
基础案例
from pyzbar.pyzbar import decode
from PIL import Image
import cv2
import numpy as np
# 从图片文件识别
def decode_qr_from_file(image_path):
img = Image.open(image_path)
codes = decode(img)
for code in codes:
print(f"二维码内容: {code.data.decode('utf-8')}")
print(f"二维码类型: {code.type}")
print(f"位置: {code.rect}")
return codes
# 从OpenCV图像识别
def decode_qr_from_cv2(image):
# 转换为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 使用pyzbar解码
codes = decode(gray)
for code in codes:
data = code.data.decode('utf-8')
print(f"识别结果: {data}")
# 绘制识别框
(x, y, w, h) = code.rect
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 显示内容
cv2.putText(image, data, (x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
return image, codes
# 使用示例
if __name__ == "__main__":
# 识别图片文件
result = decode_qr_from_file("qrcode.png")
# 识别摄像头捕获的图像
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
result_frame, codes = decode_qr_from_cv2(frame)
cv2.imshow("QR Scanner", result_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
使用OpenCV内置解码器
import cv2
import numpy as np
def decode_qr_opencv(image_path):
# 初始化二维码检测器
qr_detector = cv2.QRCodeDetector()
# 读取图片
img = cv2.imread(image_path)
# 检测并解码
data, points, straight_qrcode = qr_detector.detectAndDecode(img)
if data:
print(f"识别内容: {data}")
print(f"位置点: {points}")
# 绘制检测框
if points is not None:
points = points.astype(int)
for i in range(len(points[0])):
cv2.circle(img, tuple(points[0][i]), 5, (0, 255, 0), -1)
cv2.line(img, tuple(points[0][i]),
tuple(points[0][(i+1) % len(points[0])]),
(0, 255, 0), 2)
cv2.imshow("QR Code", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
return data
# 批量识别多个二维码
def decode_multiple_qr(image_path):
img = cv2.imread(image_path)
qr_detector = cv2.QRCodeDetector()
# 设置解码参数
qr_detector.setEpsX(0.5) # 精度参数
qr_detector.setEpsY(0.5)
data, points, _ = qr_detector.detectAndDecodeMulti(img)
if data:
for i, (d, p) in enumerate(zip(data, points)):
print(f"二维码 {i+1}: {d}")
else:
print("未检测到二维码")
return data, points
if __name__ == "__main__":
decode_qr_opencv("test_qr.png")
decode_multiple_qr("multi_qr.png")
实战:批量处理文件夹中的二维码
import os
from pathlib import Path
from pyzbar.pyzbar import decode
from PIL import Image
import pandas as pd
def batch_decode_qr(folder_path, output_file="results.csv"):
results = []
# 支持的图片格式
extensions = ['.png', '.jpg', '.jpeg', '.bmp', '.gif']
# 遍历文件夹
for file_path in Path(folder_path).rglob('*'):
if file_path.suffix.lower() in extensions:
try:
# 识别二维码
img = Image.open(file_path)
codes = decode(img)
for code in codes:
result = {
'filename': file_path.name,
'path': str(file_path),
'content': code.data.decode('utf-8'),
'type': code.type,
'width': code.rect.width,
'height': code.rect.height
}
results.append(result)
print(f"✅ {file_path.name}: {result['content']}")
except Exception as e:
print(f"❌ {file_path.name}: 识别失败 - {str(e)}")
# 保存结果到CSV
if results:
df = pd.DataFrame(results)
df.to_csv(output_file, index=False, encoding='utf-8-sig')
print(f"\n共识别 {len(results)} 个二维码,结果已保存到 {output_file}")
return results
# 使用示例
if __name__ == "__main__":
results = batch_decode_qr("./qrcodes/", "decoded_results.csv")
高级:预处理提升识别率
import cv2
import numpy as np
from pyzbar.pyzbar import decode
def preprocess_image(image):
"""图像预处理,提高二维码识别率"""
# 1. 转换为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 2. 高斯模糊去噪
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# 3. 自适应阈值二值化
binary = cv2.adaptiveThreshold(blurred, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV, 11, 2)
# 4. 形态学操作(可选)
kernel = np.ones((3, 3), np.uint8)
morph = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)
return morph
def enhanced_qr_decode(image_path):
"""增强版二维码识别"""
# 读取原图
img = cv2.imread(image_path)
# 方法1:直接识别
codes1 = decode(img)
# 方法2:预处理后识别
processed = preprocess_image(img)
codes2 = decode(processed)
# 方法3:调整图像大小
resized = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
codes3 = decode(resized)
# 合并所有结果,去重
all_codes = []
seen = set()
for codes in [codes1, codes2, codes3]:
for code in codes:
data = code.data.decode('utf-8')
if data not in seen:
seen.add(data)
all_codes.append(code)
return all_codes
# 使用示例
if __name__ == "__main__":
codes = enhanced_qr_decode("blurry_qr.jpg")
for code in codes:
print(f"识别结果: {code.data.decode('utf-8')}")
使用建议
-
选择合适的库
- 简单场景:
pyzbar+PIL - 需要图像处理:
OpenCV - 复杂场景:组合使用
- 简单场景:
-
优化技巧
- 确保二维码清晰,光线充足
- 图像预处理(去噪、增强对比度)
- 多角度识别(旋转、缩放)
-
错误处理
- 添加重试机制
- 日志记录
- 异常捕获
这些案例涵盖了从基础到进阶的二维码识别方法,可以根据实际需求选择合适的方案。