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

Ubuntu环境运行MobileSAM代码遇RuntimeError问题求助

解决Ubuntu下Ultralytics SAM推理的RuntimeError问题

针对你遇到的RuntimeError: Non-empty 4D data tensor expected but got a tensor with sizes [1, 0, 576, 1024]错误,以下是几个可行的解决方向:

1. 修复图像通道格式

OpenCV读取视频帧默认返回BGR格式,而Ultralytics模型期望RGB输入。Mac环境可能隐式处理了通道转换,但Ubuntu下需要手动转换:

while capture.isOpened():
    ret, frame = capture.read()
    if not ret:
        break
    frame = cv2.resize(frame, (640,480)) 
    # 新增:转换BGR到RGB
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    print('start interence... , ', type(frame), frame.shape)  # 打印形状确认是(480,640,3)
    t1 = time.time()
    results = model.predict(frame) # Inference
    # ... 后续代码不变

2. 验证输入帧的有效性

在推理前添加检查,确保读取的帧是有效的3通道图像,避免空帧或异常通道数的输入:

while capture.isOpened():
    ret, frame = capture.read()
    if not ret:
        break
    frame = cv2.resize(frame, (640,480)) 
    # 新增:检查图像维度
    if frame.ndim != 3 or frame.shape[2] != 3:
        print(f"Skipping invalid frame with shape: {frame.shape}")
        continue
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    # ... 后续代码不变

3. 重新安装带完整解码器的OpenCV

Ubuntu下默认的opencv-python可能缺少MOV文件的解码组件,导致读取的帧异常。卸载现有版本后安装带ffmpeg支持的版本:

pip uninstall -y opencv-python
pip install opencv-contrib-python  # 包含更多解码器

4. 显式指定模型运行设备

由于你使用CUDA环境,显式指定模型设备可以避免张量在CPU/GPU间转换时的维度异常:

model = SAM("mobile_sam.pt").to('cuda' if torch.cuda.is_available() else 'cpu')

错误原因说明

该错误的核心是模型接收到的输入张量通道维度为0,说明输入帧在读取或预处理过程中丢失了颜色通道信息。Mac与Ubuntu的环境差异主要体现在OpenCV的解码器配置、图像格式默认处理逻辑上,导致相同代码在不同系统表现不一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 02:13:28