Depth Anything强大的单目深度估计Python与C++模型部署

引言

最近看到一个叫Depth Anything单目深度估计模型火了,于是抽空把代码和模型下载下来体验了一下,发现确实是很强大。
论文链接:https://arxiv.org/pdf/2401.10891.pdf
代码链接:https://github.com/LiheYoung/Depth-Anything
项目主页: https://depth-anything.github.io/

本文只记录如何使用官方代码跑demo,以及如何导出onnx模型并用onnxruntime做部署。
在这里插入图片描述

1. 使用官方代码跑demo

首先从GitHub把代码clone下来:

git clone https://github.com/LiheYoung/Depth-Anything

然后安装依赖库:

cd Depth-Anything
pip install -r requirements.txt

依赖库比较少,搭建环境非常简单,装好以后就可以跑demo了。如果是输入图像,那么可以执行下面的脚本:

python run.py --encoder <vits | vitb | vitl> --img-path <img-directory | single-img | txt-file> --outdir <outdir>

比如:

python run.py --encoder vitb --img-path ../test.jpg --outdir output/

--img-path参数可以是单张图像的路径、存放多张图片的文件夹的路径、存放一系列图像路径的TXT文件的路径。目前官方发布了三个模型:depth_anything_vits14.pth,depth_anything_vitb14.pth,depth_anything_vitl14.pth,分别与参数里的vits, vitb,vitl对应。执行上面的命令后,会自动从Huggingface的网站上下载对应的模型。「不过需要注意的是,国内目前无法访问Huggingface。怎么办呢?不用慌,我们可以使用Huggingface的镜像网站。首先在命令行执行下面的命令设置一下环境变量:

export HF_ENDPOINT=https://hf-mirror.com

然后再运行run.py脚本就可以愉快地跑模型了,脚本会把结果输出到--outdir参数指定的目录中。下面是我用nuScenes数据集中的图片跑出

如果需要跑视频,那么可以用run_video.py脚本:

python run_video.py --encoder vitb --video-path assets/examples_video --outdir output/

Python Onnx模型部署

2.1 导出onnx模型

导出onnx模型的方法可以参考下面这个仓库:

https://github.com/fabio-sim/Depth-Anything-ONNX

把代码下载下来后运行export.py脚本即可导出onnx模型:

python export.py --model s # s对应vits模型

导出的onnx模型默认存放在weights/目录下。在这个脚本中,同样会去Huggingface网站上下载PyTorch模型,因此需要用镜像网站替换一下。替换方法很简单,就是把代码中指定的链接将huggingface.co直接替换为hf-mirror.com

depth_anything.to(device).load_state_dict(
      torch.hub.load_state_dict_from_url(
          f"https://hf-mirror.com/spaces/LiheYoung/Depth-Anything/resolve/main/checkpoints/depth_anything_vit{model}14.pth",
          map_location="cpu",
      ),
      strict=True,
  )

另外,这个脚本导出onnx模型的时候是使用的动态参数模型,如果不想用动态参数可以把dynamic_axes参数去掉改成静态模式。导出的onnx模型还可以使用onnx-simplifier工具简化一下。

2.2 用onnxruntime部署onnx模型

部署Depth Anything模型也是差不多的流程。加载好onnx模型后,首先需要对输入图像做预处理,预处理的时候需要做减均值再除以标准差对图像数据做规范化,其他处理操作与YOLOv8RT-DETR是一样的。预处理函数preprocess的实现如下:

def preprocess(
    bgr_image,
    width,
    height,
    mean=[123.675, 116.28, 103.53],
    std=[58.395, 57.12, 57.375],
):
    image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)
    image = cv2.resize(image, (width, height)).astype(np.float32)
    image = (image - mean) / std
    image = np.transpose(image, (2, 0, 1)).astype(np.float32)
    input_tensor = np.expand_dims(image, axis=0)
    return input_tensor

输入数据准备好以后,就可以送入模型进行推理:

outputs = session.run(None, {session.get_inputs()[0].name: input_tensor})

得到模型推理结果后,只需要做一点简单的后处理操作就可以了:

depth = outputs[0][0]  
depth = np.transpose(depth, [1, 2, 0]) #chw->hwc

depth = cv2.normalize(depth,None, 0,255,cv2.NORM_MINMAX,cv2.CV_8UC1)
colormap = cv2.applyColorMap(depth,cv2.COLORMAP_INFERNO)
colormap = cv2.resize(colormap,(image_width,image_height))
combined_results = cv2.hconcat([image, colormap])

后处理的时候首先调用OpenCVnormalize函数将深度图的像素值调整到[0,255]的范围内,然后调用applyColorMap函数对深度图进行伪彩色化:
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

模型输入尺寸设置为518x518batch size设置为1,在GeForce RTX 3090显卡上3个模型的耗时如下:

模型模型精度耗时
depth_anything_vits14.onnxFP3216 ms
depth_anything_vitb14.onnxFP3242 ms
depth_anything_vitl14.onnxFP3290 ms

C++ Onnx模型部署

#include "dpt.h"

Dpt::Dpt()
{
    blob_pool_allocator.set_size_compare_ratio(0.f);
    workspace_pool_allocator.set_size_compare_ratio(0.f);
}


int Dpt::load(std::string param_path, std::string bin_path, int _target_size, 
    const float* _mean_vals, const float* _norm_vals, bool use_gpu)
{
    dpt_.clear();
    blob_pool_allocator.clear();
    workspace_pool_allocator.clear();

    ncnn::set_cpu_powersave(2);
    ncnn::set_omp_num_threads(ncnn::get_big_cpu_count());

    dpt_.opt = ncnn::Option();

#if NCNN_VULKAN
    dpt_.opt.use_vulkan_compute = use_gpu;
#endif

    dpt_.opt.num_threads = ncnn::get_big_cpu_count();
    dpt_.opt.blob_allocator = &blob_pool_allocator;
    dpt_.opt.workspace_allocator = &workspace_pool_allocator;

   /* char parampath[256];
    char modelpath[256];
    sprintf(parampath, "dpt%s.param", modeltype);
    sprintf(modelpath, "dpt%s.bin", modeltype);*/

    dpt_.load_param(param_path.c_str());
    dpt_.load_model(bin_path.c_str());

    target_size_ = _target_size;
    mean_vals_[0] = _mean_vals[0];
    mean_vals_[1] = _mean_vals[1];
    mean_vals_[2] = _mean_vals[2];
    norm_vals_[0] = _norm_vals[0];
    norm_vals_[1] = _norm_vals[1];
    norm_vals_[2] = _norm_vals[2];
    
    color_map_ = cv::Mat(target_size_, target_size_, CV_8UC3);

    return 0;
}

int Dpt::detect(const cv::Mat& rgb, cv::Mat& depth_color)
{

    int width = rgb.cols;
    int height = rgb.rows;

    // pad to multiple of 32
    int w = width;
    int h = height;
    float scale = 1.f;
    if (w > h)
    {
        scale = (float)target_size_ / w;
        w = target_size_;
        h = h * scale;
    }
    else
    {
        scale = (float)target_size_ / h;
        h = target_size_;
        w = w * scale;
    }

    ncnn::Mat in = ncnn::Mat::from_pixels_resize(rgb.data, ncnn::Mat::PIXEL_RGB, width, height, w, h);

    // pad to target_size rectangle
    int wpad = target_size_ - w;
    int hpad = target_size_ - h;
    ncnn::Mat in_pad;
    ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 0.f);

    in_pad.substract_mean_normalize(mean_vals_, norm_vals_);

    ncnn::Extractor ex = dpt_.create_extractor();

    ex.input("image", in_pad);

    ncnn::Mat out;
    ex.extract("depth", out);

    cv::Mat depth(out.h, out.w, CV_32FC1, (void*)out.data);
    cv::normalize(depth, depth, 0, 255, cv::NORM_MINMAX, CV_8UC1);
    cv::applyColorMap(depth, color_map_, cv::ColormapTypes::COLORMAP_INFERNO);
    cv::resize(color_map_(cv::Rect(wpad / 2, hpad / 2, w, h)), depth_color, rgb.size());

    return 0;
}

int Dpt::draw(cv::Mat& rgb, cv::Mat& depth_color)
{
    cv::cvtColor(depth_color, rgb, cv::COLOR_RGB2BGR);

    return 0;
}

最终的结果如下:
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
源码下载地址:https://download.youkuaiyun.com/download/matt45m/89616293

<think>好的,用户想要复现AirSLAM的教程或实现指南,但目前没有直接相关的资料。我需要先理解AirSLAM是什么。根据名称推测,AirSLAM可能是一种用于无人机或空中机器人的SLAM(同步定位地图构建)技术。SLAM通常涉及传感器数据融合、实时定位和地图构建,可能需要用到激光雷达、摄像头、IMU等设备。 用户提供的引用资料都是关于不同项目的复现教程,比如Mobile ALOHA、depth anything、vulhub靶场和FCN模型。这些教程的共同点包括源码获取、环境配置、依赖安装、参数调整和测试运行。所以,我可以参考这些步骤来指导AirSLAM的复现,尽管没有直接资料。 首先,用户需要找到AirSLAM的源码,可能存放在GitHub等平台。如果官方没有提供,可能需要联系作者或查阅相关论文。接下来是环境配置,可能需要ROS(机器人操作系统)、PythonC++、CUDA等工具。安装依赖库时要确保版本兼容,例如Pytorch、TensorFlow或OpenCV。然后,数据集准备和参数调整是关键,可能需要特定的传感器数据或仿真环境。最后,测试运行并调试错误。 可能遇到的问题包括依赖冲突、硬件兼容性、数据集缺失等。需要建议用户查阅论文、社区论坛,并尝试类似项目的复现经验。同时,提醒用户注意文档的详细程度和社区支持情况,这些会影响复现的难易程度。 总结步骤:获取源码、配置环境、安装依赖、准备数据、调整参数、运行测试、调试优化。虽然没有直接教程,但通过通用方法和资源查找,用户仍可尝试复现。</think>关于AirSLAM的复现,目前公开资料中暂无详细的教程或实现指南,但可通过以下步骤尝试复现: --- ### 1. **获取源码论文** - **源码查找**:AirSLAM若为开源项目,通常在GitHub或论文附录中提供代码。尝试搜索`AirSLAM GitHub`或查看相关论文的"Implementation Details"部分[^1]。 - **论文分析**:若项目基于某篇论文(如IEEE/arXiv论文),需重点理解其算法框架,例如传感器融合策略或SLAM优化方法[^2]。 --- ### 2. **环境配置** #### 基础工具链 ```bash # 示例:Ubuntu环境下ROS安装(假设AirSLAM基于ROS) sudo apt-get install ros-noetic-desktop-full echo "source /opt/ros/noetic/setup.bash" >> ~/.bashrc ``` - **依赖库安装**:可能需要的库包括`PCL`(点云处理)、`OpenCV`(图像处理)、`Eigen`(矩阵运算)等[^4]。 --- ### 3. **代码结构依赖** - **目录解析**:典型SLAM项目包含以下模块: ``` ├── sensor_drivers/ # 传感器接口 ├── mapping/ # 地图构建 ├── localization/ # 定位算法 └── utils/ # 数据预处理 ``` - **依赖安装**:根据项目`requirements.txt`或`CMakeLists.txt`安装特定版本库,例如: ```python # 示例:Python依赖 pip install numpy==1.21.2 open3d==0.15.1 ``` --- ### 4. **数据集准备** - **公开数据集**:若AirSLAM面向无人机,可使用`EuRoC MAV`或`KAIST Urban`数据集[^3]。 - **数据格式转换**:可能需要将原始数据转换为项目要求的格式(如ROS bag或TUM格式)。 --- ### 5. **参数调试运行** - **配置文件修改**:调整`config/airslam.yaml`中的参数,例如: ```yaml # 示例:卡尔曼滤波参数 kalman_filter: process_noise: 0.1 measurement_noise: 0.5 ``` - **运行测试**: ```bash roslaunch airslam simulation.launch # ROS环境启动 ``` --- ### 6. **常见问题解决** - **依赖冲突**:使用`conda`或`virtualenv`创建隔离环境[^4]。 - **硬件兼容性**:若涉及真实无人机,需检查IMU/相机驱动兼容性。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知来者逆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值