使用YOLOv5调用摄像头目标检测时遭遇segmentation fault错误的排查
问题分析与修复方案
可能的错误点及修复步骤
1. 未检查摄像头帧读取状态
摄像头初始化失败或临时读取异常时,cam.read()返回的ret为False,此时frame是None,后续对frame的切片操作会直接触发段错误。
修复:在处理帧前先判断ret,跳过无效帧:
while(True): ret, frame = cam.read() if not ret: print("无法读取摄像头帧,重试") continue
2. 冗余且易出错的颜色转换操作
代码中存在无意义的颜色格式来回转换:
frame = frame[:, :, [2,1,0]] # BGR转RGB frame = Image.fromarray(frame) frame = cv2.cvtColor(np.array(frame), cv2.COLOR_RGB2BGR) # 又转回BGR
这不仅浪费资源,还可能在类型转换过程中引发内存错误,直接删除这段代码即可——YOLOv5模型可以直接处理OpenCV读取的BGR格式帧。
3. 依赖库版本或加载方式问题
段错误也可能源于依赖库版本不兼容:
- 建议使用官方推荐的方式安装YOLOv5,替代
torch.hub.load,避免版本冲突:
加载模型时改用本地导入:pip install yolov5from yolov5 import YOLO model = YOLO('yolov5s.pt') - 检查OpenCV版本,建议使用4.x系列,避免与PyTorch的CUDA版本冲突;若用CPU运行,确保OpenCV编译支持CPU。
- 确认摄像头权限:Linux/macOS下,确保当前用户有权限访问
/dev/video0,可执行以下命令添加权限:sudo usermod -aG video $USER
修复后的完整代码
def object_detector(): DEVICE = "cuda" if torch.cuda.is_available() else "cpu" from yolov5 import YOLO model = YOLO('yolov5s.pt') model.to(DEVICE) # 显式指定运行设备 cam = cv2.VideoCapture(0) # 提前检查摄像头是否成功打开 if not cam.isOpened(): print("无法打开摄像头") return while(True): ret, frame = cam.read() if not ret: print("读取帧失败,重试...") continue result = model(frame, size=640) cv2.imshow('YOLO', np.squeeze(result.render())) if cv2.waitKey(1) & 0xFF == ord('q'): break cam.release() cv2.destroyAllWindows()
内容的提问来源于stack exchange,提问作者e.iluf
相关产品推荐
相关产品推荐

