You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3环境下PNG格式二维码解码方案求助

Python 3 解码PNG二维码的实用方案

太懂这种烦恼了!Python 2时代的二维码工具在3.x里简直是坑多多,尤其是依赖zbar的那些老包,动不动就没法用。下面给你推荐两个我日常用的、在Python3里完全靠谱的方案,附基础解码示例,上手超简单:

方案1:pyzbar + Pillow 组合

这是我最常用的轻量组合,pyzbar 是专门适配Python3的zbar绑定,配合Pillow处理图片,能搞定绝大多数普通PNG二维码。

安装依赖

先安装所需包:

pip install pyzbar pillow

小提示:Windows系统可能需要额外安装zbar的二进制依赖(搜索“zbar windows 二进制包”,把解压后的dll文件放到Python的Lib/site-packages目录下即可);Linux/macOS用户直接通过系统包管理器安装zbar就行——Ubuntu用sudo apt-get install libzbar0,macOS用brew install zbar。

基础解码示例

from PIL import Image
from pyzbar.pyzbar import decode

# 加载目标PNG二维码图片
qr_img = Image.open("your_qr_code.png")

# 执行解码
decoded_results = decode(qr_img)

# 处理并输出结果
if decoded_results:
    for result in decoded_results:
        # 把二进制数据转成UTF-8文本
        print("解码内容:", result.data.decode("utf-8"))
        # 可选:获取二维码在图片中的位置坐标
        print("二维码位置:", result.rect)
else:
    print("未识别到有效二维码")

方案2:opencv-python + pyzbar 组合

如果你的二维码图片存在模糊、畸变或者背景干扰,用OpenCV先做预处理再解码,识别成功率会更高。

安装依赖

pip install opencv-python pyzbar

基础解码示例

import cv2
from pyzbar.pyzbar import decode

# 用OpenCV读取PNG图片
img = cv2.imread("your_qr_code.png")

# 转灰度图(可选步骤,能提升复杂场景下的识别率)
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 执行解码
decoded_results = decode(gray_img)

# 输出结果
if decoded_results:
    for result in decoded_results:
        print("解码内容:", result.data.decode("utf-8"))
else:
    print("未识别到有效二维码")

额外小推荐

还有个轻量包zbarlight也能实现解码,但它的兼容性不如上面两个方案稳定,所以优先推荐前两种。

内容的提问来源于stack exchange,提问作者phil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:29:58