Home » Compiling C++ Code Using Caffe

Compiling C++ Code Using Caffe

by Jack Simpson

As part of my PhD project, I have been writing a program in C++ to track hundreds of bees that I have tagged and to identify the pattern on the tags. Initially, I had thought that recognising the tags would be rather simplistic – I could threshold out the tags that are reflective under IR light, and then measure the shape of the object within the tag. Unfortunately, the tags lost their reflectiveness after a short period of time and become smeared (amongst other issues), and thus I had to turn to machine learning to try to find a solution to my recognition problem.

To cut a long story short, the deep learning framework Caffe helped me to solve this problem after a lot of frustration (on the positive side I did learn a lot about machine learning in the process). However, there is one thing that I found surprisingly frustrating when using this framework: compiling your own standalone C++ program that linked to Caffe. For anyone in the same situation as me, this is how to achieve this (keeping in mind I was not using GPUs):

 

  1. At the top of your .cpp program which is linking to the Caffe library, you will need to make the following definition:
    #define CPU_ONLY
  2. Now if we try to compile anything now, Caffe will make this complaint:
    caffe/proto/caffe.pb.h: No such file or directory
    Some of the header files are missing from the Caffe include directory. Thus, you’ll need to generate them with these commands from within the Caffe root directory:
    protoc src/caffe/proto/caffe.proto --cpp_out=.
    mkdir include/caffe/proto
    mv src/caffe/proto/caffe.pb.h include/caffe/proto
  3. Finally, I copied libcaffe.so into /usr/lib and the caffe directory containing the header libraries ($caffe_root/include/caffe) into the /usr/include directory. To compile this on a Mac (after installing OpenBLAS with Homebrew), I just had to run:
    g++ classification.cpp -lcaffe -lglog -lopencv_core -lopencv_highgui -lopencv_imgproc -I /usr/local/Cellar/openblas/0.2.14_1/include -L /usr/local/Cellar/openblas/0.2.14_1/lib -o classifier
  4. Alternatively, you could do what I did on my Linux machine and instead of copying header files, I just linked directly to those directories when I compiled:
    g++ classification.cpp -lcaffe -lglog -lopencv_core -lopencv_highgui -lopencv_imgproc -I ~/caffe/include -L ~/caffe/build/lib -I /usr/local/Cellar/openblas/0.2.14_1/include -L /usr/local/Cellar/openblas/0.2.14_1/lib -o classifier

You may also like