caffeCPU和gpu有什么区别 caffecpu

如何调用训练好的caffemodel你想调用你的模型, 最简单的办法是看examples/cpp_classification里面的cpp文件, 那是教你如何调用caffe获取分类结果的…(你没接触过caffe的话, 建议你直接按照这个文件来操作可能会比较简单, 下面我的代码我也不知道没接触过caffe的人看起来难度会有多大)
不过那个代码我看着不太习惯, 所以之前自己稍微写了一个简易的版本, 不知道怎么上传附件, 懒人一个就直接把代码贴在最后了 。
先简单解释一下如何使用, 把这个代码复制到一个头文件中, 然后放在examples里面一个自己创建的文件夹里面, 然后写一个main函数调用这个类就可以了, 比如:
【caffeCPU和gpu有什么区别 caffecpu】复制, 保存到caffe/examples/myproject/net_operator.hpp, 然后同目录下写一个main.cpp, 在main函数里面#include “net_operator.hpp”, 就可以使用这个类了:
const string net_prototxt = “…”; // 你的网络的prototxt文件, 用绝对路径, 下面同理
const string pre_trained_file = “…”; // 你训练好的.caffemodel文件
const string img_path = “…”; // 你要测试的图片路径
// 创建NetOperator对象
NetOperator net_operator(net_prototxt, pre_trained_file);
Blob *blob = net_operator.processImage(img_path);
// blob就得到了最后一层的输出结果, 至于blob里面是怎么存放数据的, 你需要去看看官网对它的定义
写完main.cpp之后, 到caffe目录下, make, 然后它会编译你写的文件, 对应生成的可执行文件 。 比如按我上面写的那样, make之后就会在caffe/build/examples/myproject文件夹里面生成一个main.bin, 执行这个文件就可以了 。 因为生成的可执行文件并不是直接在代码目录下, 所以前面我建议你写的路径用绝对路径
另外如果你要获取的不是最后一层的输出, 你需要修改一下processImage函数的返回值, 通过NetOperator的成员变量net_来获取你需要的blob, 比如有个blob名称为”label”, 你想获取这个blob, 可以通过net_->blob_by_name(“label”)来获取, 当然获取到的是shared_ptr<Blob >类型的, 搜一下boost shared_ptr就知道跟普通指针有什么不同了
好了, 接下来是贴代码了:
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace caffe; // NOLINT(build/namespaces)
using std::string;
class NetOperator
public:
NetOperator(const string& net_prototxt);
NetOperator(const string& net_prototxt, const string& trained_file);
~NetOperator() { }
int batch_size() { return batch_size_; }
Blob* processImage(const string &img_path, bool is_color = true);
Blob* processImages(const vector &img_paths, bool is_color = true);
private:
void createNet(const string& net_prototxt);
// read the image and store it in the idx position of images in the blob
void readImageToBlob(const string &img_path, int idx = 0, bool is_color = true);
shared_ptr<Net > net_;
cv::Size input_geometry_;
int batch_size_;
int num_channels_;
Blob* input_blob_;
TransformationParameter transform_param_;
shared_ptr<DataTransformer > data_transformer_;
Blob transformed_data_;
NetOperator::NetOperator(const string& net_prototxt) {
createNet(net_prototxt);
NetOperator::NetOperator(const string& net_prototxt, const string& trained_file) {
createNet(net_prototxt);
net_->CopyTrainedLayersFrom(trained_file);
void NetOperator::createNet(const string& net_prototxt) {

特别声明:本站内容均来自网友提供或互联网,仅供参考,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。