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

Depth-Anything模型转CoreML格式遇iOS导入异常求助

问题描述

我正在将depth-anything PyTorch模型转换为CoreML格式,通过Google Colab完成转换流程,已参考相关Notebook完成模型推理,但在iOS端导入转换后的模型时遇到异常:

  • 使用默认mlprogram后端转换的模型,iOS导入时报错(报错截图:Exception while importing mlprogram backend)
  • 使用neuralnetwork后端转换的模型,iOS导入时出现无限加载

转换核心代码如下:

# Installing all needed extensions
!pip install coremltools
# ...

import coremltools as ct
import torch

# Convert the PyTorch model to TorchScript
traced_model = torch.jit.trace(depth_anything, torch.rand(1, 3, 518, 518))

# Convert the TorchScript model to CoreML
model_coreml = ct.convert(
    traced_model,
    inputs=[ct.ImageType(name="input_1", shape=(1, 3, 518, 518), scale=1/255.0)]
)

output = model_coreml._spec.description.output[0]
output.type.imageType.colorSpace = ct.proto.FeatureTypes_pb2.ImageFeatureType.ColorSpace.Value('RGB')
output.type.imageType.width = 518
output.type.imageType.height = 518

# Save the modified CoreML model
print(model_coreml)
model_coreml.save('/content/drive/MyDrive/trained_models/depth9.mlpackage')

已尝试以下方法但均无效:

  • 手动设置输入schema元数据
  • 切换转换后端为neuralnetwork
  • 修改输出颜色空间为BGR/GRAYSCALE
解决方案

1. 修复模型追踪问题,确保TorchScript完整捕捉模型逻辑

depth-anything部分模块可能包含动态操作,torch.jit.trace无法完全解析,建议改用torch.jit.script,或在eval模式下带校验追踪:

depth_anything.eval()  # 必须切换到eval模式,避免dropout等训练层干扰
# 方案1:用script替代trace,更适合含动态逻辑的模型
traced_model = torch.jit.script(depth_anything)
# 方案2:带校验的trace,确保追踪逻辑正确
traced_model = torch.jit.trace(
    depth_anything, 
    torch.rand(1, 3, 518, 518), 
    check_trace=True,  # 校验追踪结果与原模型是否一致
    check_inputs=[torch.rand(1, 3, 518, 518)]  # 多输入校验
)

2. 正确定义输入输出类型,避免手动修改spec的错误

depth-anything输出为单通道深度图,不要手动将输出设为RGB,应在转换时明确输出类型为灰度图或张量:

# 转换为输出张量(推荐,iOS端处理更灵活)
model_coreml = ct.convert(
    traced_model,
    inputs=[ct.ImageType(
        name="input_1", 
        shape=(1, 3, 518, 518), 
        scale=1/255.0, 
        color_space="RGB"  # 匹配模型输入的颜色空间
    )],
    outputs=[ct.TensorType(name="depth_output")],
    convert_to="mlprogram",
    minimum_deployment_target=ct.target.iOS16  # 适配iOS版本
)

# 或转换为灰度图像输出
model_coreml = ct.convert(
    traced_model,
    inputs=[ct.ImageType(
        name="input_1", 
        shape=(1, 3, 518, 518), 
        scale=1/255.0, 
        color_space="RGB"
    )],
    outputs=[ct.ImageType(
        name="depth_map", 
        color_space="GRAYSCALE", 
        shape=(1, 1, 518, 518)
    )],
    convert_to="mlprogram",
    minimum_deployment_target=ct.target.iOS16
)

3. 提前验证转换后的模型有效性

在Colab中用coremltools测试模型推理,排除转换过程中的错误:

import numpy as np
from PIL import Image

# 准备测试输入
test_img = Image.open("test.jpg").resize((518, 518))
test_input = np.array(test_img).astype(np.float32) / 255.0
test_input = np.transpose(test_input, (2, 0, 1))[None, ...]  # 转换为(1,3,518,518)

# 运行CoreML推理
prediction = model_coreml.predict({"input_1": test_input})
print("推理输出形状:", list(prediction.values())[0].shape)

4. iOS端导入的适配要点

  • 若使用mlprogram格式模型,确保iOS项目部署目标≥iOS 16
  • 输入图像预处理需与转换时一致:将图像像素值除以255,保持RGB通道顺序
  • 导入模型时,不要修改输入输出的维度,严格匹配转换时的(1,3,518,518)输入形状

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:34:58