#ifndef CPU_ONLY
#define CPU_ONLY
#endif
#include <string>
#include <vector>
#include <iostream>
#include "caffe/caffe.hpp"
#include "caffe/layers/input_layer.hpp"
#include "caffe/layers/conv_layer.hpp"
#include "caffe/net.hpp"
#include "caffe/blob.hpp"
#include <opencv2/opencv.hpp>
using namespace caffe;
int main(){
char * proto = "/home/wdh/models/mobilenet/mobilenet_deploy.prototxt";
char * model = "/home/wdh/models/mobilenet/mobilenet.caffemodel";
Phase phase = TEST;
Caffe::set_mode(Caffe::CPU);
boost::shared_ptr< Net<float> > net (new Net<float>(proto,phase));
net->CopyTrainedLayersFrom(model);
std::cout<<"load net and params done!"<<std::endl;
cv::Mat img = cv::imread("/home/wdh/caffe/examples/images/cat.jpg");
cv::resize(img,img,cv::Size(224,224));
float * data = (float*)malloc(3*224*224*sizeof(float));
int channels = 3;
int height = 224;
int width = 224;
for(int i=0;i<height;++i){
for(int j=0;j<width;++j){
for(int c=0;c<channels;++c){
data[c*height*width + i*width + j] = img.ptr<uchar>(i)[j*channels+c] / 255.0;
}
}
}
Blob<float>* input_blobs = net->input_blobs()[0];
std::cout<<input_blobs->channels()<<","<<input_blobs->height()<<","<<input_blobs->width()<<std::endl;
memcpy(input_blobs->mutable_cpu_data(), data,
sizeof(float) * input_blobs->count());
net->Forward();
Blob<float>* output_blobs = net->output_blobs()[0];
std::cout<<output_blobs->channels()<<","<<output_blobs->height()<<","<<output_blobs->width()<<std::endl;
int max_id = 0;
float max_p = 0.0;
for(int i=0;i<output_blobs->channels();++i){
float value = output_blobs->data_at(0,i,0,0);
if(value > max_p){
max_p = value;
max_id = i;
}
std::cout<<value<<std::endl;
}
std::cout<<"max_id:"<<max_id<<",max_p"<<max_p<<std::endl;
free(data);
return 0;
}
cmake_minimum_required(VERSION 3.13)
project(helloworld)
set(out_name hellocaffe)
#include_directories(/home/wdh/caffe/include)
include_directories(/home/wdh/caffe/build/src)
add_executable(${out_name} helloworld.cpp)
link_directories(/home/wdh/caffe/build/lib)
link_directories(/usr/lib/x86_64-linux-gnu)
target_link_libraries(${out_name} caffe boost_system opencv_imgcodecs opencv_imgproc opencv_core glog)