我的知识记录

Python 识别二维码内容:pyzbar 解码图片教程

Python 用 pyzbar + Pillow 识别本地图片中的二维码内容,支持一张图多个码、批量识别文件夹,给出完整代码和 Windows 下 zbar 依赖安装说明。

场景痛点

手里有一堆二维码截图、海报照片,要批量提取里面的链接或文本,靠手机一个个扫太慢。Python 的 pyzbar 库能直接从图片里解码出二维码内容,配合 Pillow 读文件,一行一行跑文件夹,几分钟就能把几百张图的二维码内容全导出来。

用到的库

pip install pyzbar Pillow

Windows 下还需要装 zbar 动态库:pip install pyzbar 一般自带;若报 ImportError: Unable to find zbar,请去 zbar 官方 下载预编译 dll 放进 Python 目录。

完整代码

from pyzbar.pyzbar import decode
from PIL import Image
import os


def decode_one_image(image_path):
"""识别单张图片里的所有二维码,返回字符串列表"""
img = Image.open(image_path)
results = decode(img)
if not results:
print(f"{image_path}: 未识别到二维码")
return []

texts = []
for idx, obj in enumerate(results, 1):
text = obj.data.decode("utf-8", errors="replace")
print(f"{image_path} 第 {idx} 个码:{text}")
texts.append(text)
return texts


def decode_folder(folder):
"""批量识别文件夹下所有图片中的二维码"""
exts = (".png", ".jpg", ".jpeg", ".bmp")
all_texts = {}
for name in sorted(os.listdir(folder)):
if not name.lower().endswith(exts):
continue
path = os.path.join(folder, name)
texts = decode_one_image(path)
if texts:
all_texts[name] = texts

# 把结果写到 txt 汇总
out = os.path.join(folder, "qr_result.txt")
with open(out, "w", encoding="utf-8") as f:
for name, texts in all_texts.items():
f.write(f"=== {name} ===\n")
for t in texts:
f.write(t + "\n")
f.write("\n")
print(f"汇总结果已写入:{out}")


def main():
# 识别单张
decode_one_image("qr_basic.png")

# 批量识别整个文件夹
decode_folder("./qrcodes")


if __name__ == "__main__":
main()

代码讲解

  • Image.open(path) 用 Pillow 打开图片,支持 PNG、JPG、BMP 等常见格式。
  • decode(img) 返回一个列表,每个元素是 Decoded 对象,.data 就是二维码里的原始字节,用 .decode("utf-8") 转字符串。
  • 一张图里如果有多个二维码,decode 会一次性全部返回,循环取出即可。
  • decode_folder 遍历目录里所有图片,识别后把结果写入 qr_result.txt,方便后续 Excel 导入。

运行结果

运行后控制台逐行打印每张图识别到的二维码内容,未识别到的图会提示"未识别到二维码"。最终在目标文件夹生成 qr_result.txt,每张图占一段,方便归档。

注意事项

  • Windows 下 pyzbar 报错通常是缺 zbar dll,建议直接用 Anaconda 或装预编译 wheel。
  • 图片模糊、倾斜、反光会识别失败,识别前可先用 Pillow 转灰度、二值化提升成功率。
  • 一张图里塞太多二维码会导致定位点混乱,单图建议不超过 4 个。
  • 识别条码(Code128、EAN13 等)也是 decode() 同一个函数,根据 obj.type 区分。
  • 中文内容如果识别出来是乱码,多半是二维码本身用 GBK 编码生成的,把解码改成 errors="replace" 后再试 GBK。

Python 识别二维码内容:pyzbar 解码图片教程

标签:

更新时间:2026-09-14 20:40:37

上一篇:Python 钉钉机器人 Webhook 推送通知:加签与消息示例

下一篇:Python 每天定时运行脚本教程:固定时间自动执行任务