整合Caffe和ROS

Caffe是非常流行的深度学习库,ROS是当下使用最广泛的机器人库(我觉得叫操作系统有些过),把Caffe和ROS一起使用就很方便地将深度学习技术应用到机器人上,但是现在的Caffe各种fork(通常都是对基本的卷积神经网络扩展),所以使用Caffe最方便的还是从源码(和fork)编译。所以这里记录如何将Caffe作为ROS模块的库使用。

首先要安装ROS和Caffe需要库:

# Install Caffe dependencies
sudo apt-get install libprotobuf-dev libleveldb-dev libsnappy-dev libopencv-dev libhdf5-serial-dev protobuf-compiler
sudo apt-get install --no-install-recommends libboost-all-dev
sudo apt-get install libgflags-dev libgoogle-glog-dev liblmdb-dev
sudo apt-get install libatlas-base-dev

 

创建ROS工作环境,创建ROS模块,并添加Caffe为git子模块:

catkin_create_pkg caffe_example
cd caffe_example

git init .
mkdir lib
cd lib
git submodule add https://github.com/NVIDIA/caffe  # 这是NVIDIA的fork,原 https://github.com/BVLC/caffe
echo 'add_subdirectory(caffe)' >> CMakeLists.txt

cd ..
echo 'add_subdirectory(lib)' >> CMakeLists.txt

roscd # to devel directory
cd ..
catkin_make

 

但是编译会有如下错误:

CMake Error at caffe_example/lib/caffe/src/gtest/CMakeLists.txt:1 (add_library):
  add_library cannot create target "gtest" because another target with the
  same name already exists.  The existing target is a shared library created
  in source directory "/usr/src/gtest".  See documentation for policy CMP0002
  for more details.

原因是Caffe自带了gtest源码,与ROS使用的Ubuntu系统中的冲突,需要修改一下cmake文件:src/caffe_example/lib/caffe/src/gtest/CMakeLists.txt
将第一行从 add_library(gtest STATIC EXCLUDE_FROM_ALL gtest.h gtest-all.cpp)
改为 add_library(caffe_gtest STATIC EXCLUDE_FROM_ALL gtest.h gtest-all.cpp)
并添加一行 set_target_properties(caffe_gtest PROPERTIES OUTPUT_NAME gtest)

注:如果想编译Caffe CPU版本,需要修改 src/caffe_example/lib/caffe/CMakeLists.txt
caffe_option(CPU_ONLY "Build Caffe without CUDA support" OFF) 中的OFF 改为 ON
再重新编译

# clean and build
rm devel -rf
rm build -rf
catkin_make

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.