macOS下使用OpenCV读取摄像头报错TypeError问题求助
macOS下摄像头条码识别代码报错排查
问题代码
import cv2 from pyzbar.pyzbar import decode import os os.system("clear") cap = cv2.VideoCapture(0) cap.set(3 , 640) cap.set(4 , 480) while True: success, img = cap.read() for barcode in decode(img): print(barcode.data) print(barcode.rect) x = barcode.data.decode('utf-8') print(x) cv2.imshow('Result', img) cv2.waitKey(1)
报错信息
Traceback (most recent call last): File "/Users/username/Documents/Pyzbar Lesson 2.py", line 21, in <module> for barcode in decode(img): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pyzbar/pyzbar.py", line 207, in decode pixels, width, height = _pixel_data(image) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pyzbar/pyzbar.py", line 173, in _pixel_data pixels, width, height = image TypeError: cannot unpack non-iterable NoneType object
问题分析
- 核心触发点:
cap.read()调用失败时,img会返回None,直接将None传入decode()函数就会触发上述报错。常见失败原因:- macOS系统未给Python授予摄像头访问权限
- 摄像头设备索引不是0(外接摄像头或多摄像头设备易出现此情况)
- 摄像头被其他程序占用
- 代码缺陷:未对
cap.read()的返回值success做校验,无法判断摄像头是否成功捕获帧。
修复方案
1. 增加帧捕获校验逻辑
修改代码,先判断帧是否捕获成功,避免传入None到解码函数:
import cv2 from pyzbar.pyzbar import decode import os os.system("clear") # 尝试不同设备索引,0不行则试1、2 cap = cv2.VideoCapture(0) cap.set(3 , 640) cap.set(4 , 480) while True: success, img = cap.read() # 校验帧捕获状态 if not success: print("无法捕获摄像头帧,请检查设备或权限") break for barcode in decode(img): print(barcode.data) print(barcode.rect) x = barcode.data.decode('utf-8') print(x) cv2.imshow('Result', img) # 按下q键退出循环 if cv2.waitKey(1) & 0xFF == ord('q'): break # 释放摄像头资源并关闭窗口 cap.release() cv2.destroyAllWindows()
2. 解决macOS摄像头权限问题
- 打开系统偏好设置 → 安全性与隐私 → 隐私 → 摄像头
- 确保运行代码的Python解释器(如Python 3.10)在允许访问摄像头的列表中
- 若列表无对应程序,点击锁图标解锁后添加
3. 调整摄像头设备索引
如果默认索引0无法访问摄像头,尝试将cv2.VideoCapture(0)中的0改为1、2等,逐个测试找到正确的设备索引。
内容的提问来源于stack exchange,提问作者Cloudi Nash
相关产品推荐
相关产品推荐

