为什么普通手机也需要单目深度
LiDAR 是 Pro 机型的专属。iPhone 12 Pro 之后只有 Pro 系列带激光雷达,标准版和 SE 一直没有。但逐像素深度这件事,需求远不止 Pro 用户:人像虚化要它、照片转 3D 要它、AR 虚拟物体被真实桌子遮挡要它、测距要它、视障辅助的空间描述也要它。
单目深度估计(monocular depth estimation)就是让一颗普通 RGB 摄像头具备这种能力。2025 年 11 月,字节 Seed 团队发布 Depth Anything 3(下称 DA3),论文进了 ICLR 2026 Oral。它对端侧最重要的两个变化:
- 输出的是 depth 而不是 disparity。DA2 是视差模型,几何精度受限于视差到深度的换算;DA3 直接预测深度加光线(depth-ray 表示),单视图输入时退化为一个单目深度估计器。
- 模型足够小。DA3-SMALL 只有 0.08B 参数(DINOv2 ViT-S/14 骨干 + DualDPT 头),Apache-2.0 授权,可商用。
官方论文口径:DA3 在单目深度上明显优于 DA2,多视图位姿精度比此前 SOTA 的 VGGT 高 35.7%、几何精度高 23.6%(ICLR 2026 版本数据,截至 2026-10-26 核对官方项目页与论文摘要)。
对我们做端侧的人来说,问题只有一个:怎么把它塞进 App,并且跑得动。
三条落地路线,先看清代价
| 路线 |
模型 |
体积 |
最低系统 |
获取方式 |
适合谁 |
| Apple 官方 Core ML 模型库 |
Depth Anything V2 Small F16 |
49.8 MB(P6 变体 19 MB) |
iOS 17 |
直接下载 mlpackage 拖进 Xcode |
想今天上线,精度够用 |
| coremltools 自己转 |
DA3-SMALL 504×504 |
约 44-55 MB |
iOS 17 |
自己写转换脚本 |
要最新精度、要控制量化 |
| Core AI(.aimodel) |
depth-anything-3-small |
未公开 |
iOS 27 |
apple/coreai-models |
新项目且能等 iOS 27 |
第三个路线得说清楚:Core AI 是 WWDC26 新推的端侧推理框架,模型格式是 .aimodel,需要 Xcode 27 和 iOS 27/macOS 27。Apple 的 coreai-models 仓库 1.0.0 已经收录 Depth Anything v3,但模型注册表里 depth-anything-3-small 目前只标了 macOS 平台,iOS recipe 还没跟上。所以现阶段要让 iPhone 用上 DA3,仍然是 Core ML 这条路最稳。
授权上的硬约束
选模型之前先看许可证,这是很多教程漏掉的:
- DA3-SMALL(0.08B)、DA3-BASE(0.12B):Apache-2.0,商用没问题。
- DA3-LARGE(0.35B)、DA3-GIANT(1.15B)、Nested 系列:CC BY-NC 4.0,不能商用。
也就是说 App Store 上架的产品,能用的只有 SMALL 和 BASE 两档。想用大模型提精度,只能自己微调小模型或换授权。
方案 A:先跑通 Apple 官方的 V2 包
这是最快的验证路径,半小时能出效果。从 Apple 的 Core ML Models 页面下载 DepthAnythingV2SmallF16.mlpackage(49.8 MB,24.8M 参数,FP16 权重与激活),拖进 Xcode 目标,Xcode 会在构建时自动编译成 .mlmodelc。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
import CoreML
import CoreVideo
final class DepthEstimator {
private let model: MLModel
init() throws {
let cfg = MLModelConfiguration()
cfg.computeUnits = .all // 关键:让 ANE 优先,别锁 .cpuOnly
guard let url = Bundle.main.url(forResource: "DepthAnythingV2SmallF16",
withExtension: "mlmodelc") else {
throw NSError(domain: "DepthEstimator", code: 1)
}
model = try MLModel(contentsOf: url, configuration: cfg)
}
func predict(pixelBuffer: CVPixelBuffer) throws -> MLMultiArray {
let input = try MLDictionaryFeatureProvider(
dictionary: ["image": MLFeatureValue(pixelBuffer: pixelBuffer)]
)
let out = try model.prediction(from: input)
guard let depth = out.featureValue(for: "depth")?.multiArrayValue else {
throw NSError(domain: "DepthEstimator", code: 2)
}
return depth
}
}
|
两个容易踩的点:
- 输入尺寸不用你自己缩放。图像类型输入(
ImageType)由 Core ML 内部做缩放,你传相机原尺寸的 CVPixelBuffer 就行,别在 Swift 层再手动 resize 一遍——重复缩放反而会让边缘出现二次插值糊化。
computeUnits 一定要显式设 .all。默认值在部分机型上会退到 CPU+GPU,实测 ANE 与 GPU 的差距在深度模型上通常是 2-3 倍。
方案 B:把 DA3 转成 Core ML
想用 DA3 就得自己转。核心难点是只导出单目深度分支:DA3 是个 any-view 模型,完整图里还有相机解码器、光线头、天空分割、3D Gaussian 分支,这些对单视图深度全是死代码,留着只会让模型体积翻几倍、ANE 编译失败。
转换脚本骨架(coremltools 9.0,2025-11-10 发布,支持 Python 3.13 与 iOS 26 目标):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
# convert_da3_mono.py
import torch
import torch.nn as nn
import coremltools as ct
from depth_anything_3.api import DepthAnything3
SIZE = 504
class MonoDepthWrapper(nn.Module):
"""只暴露单目深度路径:输入 RGB [0,1],输出 depth 与 confidence。"""
def __init__(self, net):
super().__init__()
self.net = net
# ImageNet 归一化烘进图里,Core ML 侧只需给 scale=1/255
self.register_buffer("mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))
self.register_buffer("std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))
def forward(self, x): # x: (1, 3, H, W) in [0, 1]
x = (x - self.mean) / self.std
x = x.unsqueeze(1) # (B, S, 3, H, W),S=1 即单视图
out = self.net(x)
return out["depth"].squeeze(1), out["depth_conf"].squeeze(1)
# 1) 载入官方权重
api = DepthAnything3.from_pretrained("depth-anything/DA3-SMALL")
net = api.model.eval().float()
# 2) 先跑一次 eager,确认输出形状与数值范围
wrapper = MonoDepthWrapper(net).eval()
example = torch.rand(1, 3, SIZE, SIZE)
with torch.no_grad():
ref_d, ref_c = wrapper(example)
print("depth", ref_d.shape, float(ref_d.min()), float(ref_d.max()))
# 3) trace(DA3 骨干里有 x[:, :, 0] = cam_token 的原地写,
# 必须先改成 torch.cat 等价写法,否则 trace 出的图会丢掉这个赋值)
traced = torch.jit.trace(wrapper, example, strict=False)
t_d, _ = traced(example)
err = (ref_d - t_d).abs().max().item()
assert err < 1e-3, f"trace 精度崩了: {err}"
# 4) 转 Core ML
mlmodel = ct.convert(
traced,
inputs=[ct.ImageType(name="image", shape=(1, 3, SIZE, SIZE),
scale=1.0 / 255.0, color_layout=ct.colorlayout.RGB)],
outputs=[ct.TensorType(name="depth"), ct.TensorType(name="confidence")],
compute_precision=ct.precision.FLOAT16,
minimum_deployment_target=ct.target.iOS17,
convert_to="mlprogram",
)
mlmodel.save("DepthAnythingV3_small_504.mlpackage")
|
四个必须知道的坑
- 原地写会毁掉 trace。DA3 骨干里用
x[:, :, 0] = cam_token 把相机 token 写进序列首位。torch.jit.trace 对这类原地操作捕获不完整,转出来的模型要么形状对不上,要么直接丢赋值。改写成 torch.cat([cam_token, x[:, :, 1:]], dim=2) 后再 trace。
- FP16 注意力会溢出。DINOv2 骨干的 SDPA 在 FP16 下偶发数值溢出,表现为输出深度图整体变成一片灰。判断方法:转换后拿同一张图分别跑 torch FP32 和 Core ML,算余弦相似度,正常应接近 1.000;如果掉到 0.9 以下,就把
compute_precision 换成 ct.precision.FLOAT32(体积翻倍但能出正确结果),或者只对注意力块保持 FP32。
- RoPE 频率表长度是数据相关的。DA3 的位置编码表长度取自
int(positions.max()) + 1,这在你固定输入分辨率(504×504,token 网格固定)时其实是个常量。转换前把它烘成固定常数,否则 trace 会生成动态形状分支,ANE 编译直接拒绝。
- 别忘了一次性校验。转换后务必用 2-3 张真实照片跑一遍 torch 与 Core ML 的对比,只看
depth 的 scale-aligned 相对误差,别只看形状。公开的第三方转换记录里,FP16 版本的余弦相似度能保持 1.000000,单像素相对误差在 1% 量级——这个量级对人像虚化、点云可视化完全够用。
从深度图到能用的东西
拿到 depth 和 confidence 只是中间产物。真正有用的是两件事:一张能看的深度伪彩图,和一份能投影到 3D 空间的点云。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
import CoreML
import CoreGraphics
/// 相对深度 -> jet 伪彩 CGImage,低置信度像素压成半透明
func colorize(depth: MLMultiArray, conf: MLMultiArray,
confThreshold: Float = 0.3) -> CGImage? {
let h = depth.shape[1].intValue
let w = depth.shape[2].intValue
let n = h * w
let d = depth.dataPointer.bindMemory(to: Float.self, capacity: n)
let c = conf.dataPointer.bindMemory(to: Float.self, capacity: n)
// 只用高置信度像素统计动态范围,避免天空/远景拉偏对比度
var lo = Float.greatestFiniteMagnitude, hi = -Float.greatestFiniteMagnitude
for i in 0..<n where c[i] > confThreshold {
lo = min(lo, d[i]); hi = max(hi, d[i])
}
guard hi > lo else { return nil }
var bgra = [UInt8](repeating: 0, count: n * 4)
for i in 0..<n {
let t = max(0, min(1, (d[i] - lo) / (hi - lo))) // 归一化到 0-1
bgra[i * 4 + 0] = UInt8(255 * min(1, (1 - t) * 2)) // B:近处亮
bgra[i * 4 + 1] = UInt8(255 * max(0, 1 - abs(t - 0.5) * 2))
bgra[i * 4 + 2] = UInt8(255 * min(1, t * 2)) // R:远处亮
bgra[i * 4 + 3] = c[i] > confThreshold ? 255 : 60
}
let space = CGColorSpaceCreateDeviceRGB()
let info = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)
return bgra.withUnsafeMutableBytes { buf in
guard let ctx = CGContext(data: buf.baseAddress, width: w, height: h,
bitsPerComponent: 8, bytesPerRow: w * 4,
space: space, bitmapInfo: info.rawValue) else {
return nil
}
return ctx.makeImage()
}
}
|
点云反投影则需要相机内参。注意 DA3 输出的深度是相对深度(不是米),想得到真实尺度只有两条路:用 DA3METRIC-LARGE(0.35B,Apache-2.0)按 metric_depth = focal * net_output / 300 换算,或者用 ARKit 的 LiDAR 场景深度做一次对齐。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import simd
/// 相对深度 -> 点云(尺度未知,仅用于可视化与遮挡判断)
func unproject(depth: [Float], w: Int, h: Int,
fx: Float, fy: Float, cx: Float, cy: Float) -> [simd_float3] {
var pts: [simd_float3] = []
pts.reserveCapacity(w * h / 4)
for y in stride(from: 0, to: h, by: 2) {
for x in stride(from: 0, to: w, by: 2) {
let z = depth[y * w + x]
guard z > 0 else { continue }
let X = (Float(x) - cx) * z / fx
let Y = (Float(y) - cy) * z / fy
pts.append(simd_float3(X, Y, z))
}
}
return pts
}
|
实测数据:官方给了什么,没给什么
| 模型 / 后端 |
设备 |
精度 |
耗时 |
内存峰值 |
来源 |
| DA2-Small F16 |
iPhone 16 Pro (iOS 18.3) |
FP16 |
26.2 ms |
未公布 |
Apple Core ML Models |
| DA2-Small F16 |
iPhone 15 Pro Max (iOS 17.4) |
FP16 |
33.9 ms |
未公布 |
Apple Core ML Models |
| DA2-Small 518 |
Snapdragon 8 Gen 3 / ONNX |
FP16 |
108 ms |
667 MB |
Qualcomm AI Hub |
| DA2-Small 518 |
Snapdragon 8 Elite Gen 5 / ONNX |
w8a16 |
11.9 ms |
421 MB |
Qualcomm AI Hub |
| DA3-Small 504 |
iPhone(第三方转换) |
FP16 |
未公布 |
约 300 MB |
HF 模型卡 |
| DA3-Small 504 |
M4 Max GPU |
FP16 |
15.2 ms |
未公布 |
coreai-model-zoo |
这里有个必须诚实说明的地方:DA3 在 iPhone 上的公开实测延迟目前还是空白。第三方转换的模型卡只给了 44 MB 下载体积和约 300 MB 峰值内存,没给 iPhone 上的毫秒数。按参数量的比例粗估,DA3-SMALL(0.08B)比 DA2-SMALL(0.0248B)大 3 倍多,实际延迟大概率落在 60-100 ms 区间——这个数字是我的推算,不是实测,上线前请务必用 Instruments 的 Core ML 模板在你的目标机型上量。
怎么选
- 今天就要上线、只做背景虚化或 AR 遮挡:用 Apple 官方的 DA2 Small Core ML 包。26-34 ms 的官方实测数据最可信,包也最小(P6 变体只有 19 MB)。
- 要更准的深度、能接受自己做转换和验证:转 DA3-SMALL。精度提升是实打实的,代价是多一套转换脚本和一轮数值校验。
- 面向 iOS 27 的新项目、不急着发版:跟 Core AI。
.aimodel 有 AOT 预编译和模型特化缓存,首次加载比 Core ML 快得多,但 iOS recipe 目前还没覆盖深度模型。
- Android 或跨端:别绕 Core ML 了,走 Qualcomm AI Hub 的 ONNX/QNN 预导出模型,DA2 在 Snapdragon 8 Elite Gen 5 上的 w8a16 版本只要 11.9 ms,是三个平台里最快的。
最后提醒一句:深度估计的延迟不是唯一指标,后处理往往更贵。伪彩图渲染和点云反投影如果放在主线程做,帧率会立刻掉到个位数。所有逐像素循环都挪到 DispatchQueue 的并发队列,或者干脆用 Metal compute shader 做——这一步不做,模型再快也是白搭。
文中所有模型版本、体积、延迟与授权信息均于 2026-10-26 核对官方来源(Apple Core ML Models 页面、ByteDance-Seed/Depth-Anything-3 仓库、Qualcomm AI Hub、apple/coreai-models 1.0.0 发布说明、coremltools 9.0 发布说明)。延迟数据随系统版本与芯片差异较大,请以目标设备实测为准。