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

使用pyzbar与OpenCV开发条码阅读器时遇TypeError错误求助

问题分析与解决方案

错误根源

报错TypeError: cannot unpack non-iterable NoneType object的直接原因是cv2.imread(image)返回了None——OpenCV未成功读取到目标图片文件。当将None传入pyzbar.decode()时,内部的_pixel_data函数尝试解包这个非可迭代对象,从而触发错误。

常见触发场景:

  • 图片相对路径错误,文件不在脚本预期的目录下
  • 图片文件损坏或格式不被OpenCV支持
  • 权限限制导致无法读取文件

修复步骤

1. 新增图片读取校验

在调用解码函数前,先检查图片是否成功读取,避免后续报错:

def BarcodeReader(image):
    img = cv2.imread(image)
    
    # 新增:校验图片读取结果
    if img is None:
        print(f"无法读取图片文件:{image},请检查路径是否正确或文件是否损坏")
        return
    
    # 后续解码逻辑...

2. 确保图片路径正确

优先使用绝对路径测试,避免相对路径的定位问题:

if __name__ == "__main__":
    # 替换为你的图片绝对路径
    image = r"C:\Users\galax\Documents\barcodeScanner\barcode.png"
    BarcodeReader(image)

3. 转换灰度图提升识别率

pyzbar对灰度图的识别稳定性更高,解码前可将图片转为灰度格式:

# 读取图片后添加
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
detectedBarcodes = decode(gray_img)

4. 修复代码缩进与数据类型问题

原代码中if barcode.data!="":存在缩进错误,且barcode.data是bytes类型,需修正为:

if barcode.data != b"":
    # 解码为字符串输出
    print(barcode.data.decode('utf-8'))
    print(barcode.type)

完整修复后的代码

# Importing library
import cv2
from pyzbar.pyzbar import decode

# Make one method to decode the barcode
def BarcodeReader(image):
    
    # read the image in numpy array using cv2
    img = cv2.imread(image)
    
    # 检查图片是否成功读取
    if img is None:
        print(f"无法读取图片文件:{image},请检查路径是否正确或文件是否损坏")
        return
    
    # 转换为灰度图提升识别效果
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # Decode the barcode image
    detectedBarcodes = decode(gray_img)
    
    # If not detected then print the message
    if not detectedBarcodes:
        print("Barcode Not Detected or your barcode is blank/corrupted!")
    else:
        # Traverse through all the detected barcodes in image
        for barcode in detectedBarcodes:
        
            # Locate the barcode position in image
            (x, y, w, h) = barcode.rect
            
            # Put the rectangle in image using
            # cv2 to highlight the barcode
            cv2.rectangle(img, (x-10, y-10),
                        (x + w+10, y + h+10),
                        (255, 0, 0), 2)
            
            if barcode.data != b"":
                # Print the barcode data (解码为字符串)
                print(barcode.data.decode('utf-8'))
                print(barcode.type)
                
    #Display the image
    cv2.imshow("Image", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == "__main__":
    # 使用绝对路径确保能找到图片
    image = r"C:\Users\galax\Documents\barcodeScanner\barcode.png"
    BarcodeReader(image)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 23:47:37