opencv中使用Caffe框架

Caffe,全称Convolutional Architecture for Fast Feature Embedding,是一个兼具表达性、速度和思维模块化的深度学习框架。由伯克利人工智能研究小组和伯克利视觉和学习中心开发。虽然其内核是用C++编写的,但Caffe有Python和Matlab 相关接口。Caffe支持多种类型的深度学习架构,面向图像分类和图像分割,还支持CNN、RCNN、LSTM和全连接神经网络设计。Caffe支持基于GPU和CPU的加速计算内核库,如NVIDIA cuDNN和Intel MKL。

使用
/* Find best class for the blob (i. e. class with maximal probability) */
static void getMaxClass(const Mat &probBlob, int *classId, double *classProb)
{
    Mat probMat = probBlob.reshape(1, 1); //reshape the blob to 1x1000 matrix
    Point classNumber;
    minMaxLoc(probMat, NULL, classProb, NULL, &classNumber);
    *classId = classNumber.x;
}
static std::vector<String> readClassNames(const char *filename = "/sdcard/synset_words.txt")
{
    std::vector<String> classNames;
    std::ifstream fp(filename);
    if (!fp.is_open())
    {
        LOGI("error");
        return classNames;
    }
    std::string name;
    while (!fp.eof())
    {
        std::getline(fp, name);
        if (name.length())
            classNames.push_back( name.substr(name.find(' ')+1) );
    }
    fp.close();
    return classNames;
}

void main(){
        CV_TRACE_FUNCTION();
        String modelTxt = "bvlc_googlenet.prototxt";
        String modelBin = "bvlc_googlenet.caffemodel";
        String imageFile = "/sdcard/air_plane.jpg";
        Net net;
        try {
            net = dnn::readNetFromCaffe(modelTxt, modelBin);
        }catch (cv::Exception& e) {
            LOGI("jason error %s", e.what());
        }
        Mat img = oneMat.clone();
        //GoogLeNet accepts only 224x224 BGR-images
        Mat inputBlob = blobFromImage(img, 1.0f, Size(224, 224),
                                      Scalar(104, 117, 123), false);   //Convert Mat to batch of images
        Mat prob;
        cv::TickMeter t;
        for (int i = 0; i < 10; i++)
        {
            CV_TRACE_REGION("forward");
            net.setInput(inputBlob, "data");        //set the network input
            t.start();
            prob = net.forward("prob");                          //compute output
            t.stop();
        }
        int classId;
        double classProb;
        getMaxClass(prob, &classId, &classProb);//find the best class
        std::vector<String> classNames = readClassNames();
        LOGI("Best class: %s", classNames.at(classId).c_str());
        LOGI("Probability: %f", classProb*100);
}


你可能感兴趣的:(Android,C语言,深度学习,caffe)