OpenCV3.3以上的DNN模块学习及应用(C++)

OpenCV做了近一步扩展支持所有主流的深度学习框架训练生成与导出模型数据加载,常见的有如下:

  • Caffe

  • TensorFlow

  • Torch/PyTorch 

  • 以GoogleNet Caffe模型为例。

  • 一般需要两个文件:1)模型参数    2)模型配置文件即模型框架

            bvlc_googlenet.caffemodel

            bvlc_googlenet.prototxt

  • 模型文件需要从以下地址下载即可: 下载地址

  • bvlc_googlenet.prototxt下载地址 https://gitee.com/xiemooc/codes/1mstlfu3baqo50z98ikwr51

  • 完整代码链接 https://gitee.com/xiemooc/codes/biflnt348v9p6ds5hx1jc59

  • 编程实现

  • 1. OpenCV加载一张图

     Mat testImage = imread("D:/vcprojects/images/dnn/football.jpg");
        if (testImage.empty()) {
            printf("could not load image...\n");
            return -1;
        }

    2. 声明路径,导入模型

    String modelTxt = "D:/vcprojects/images/dnn/bvlc_googlenet.prototxt";
    String modelBin = "D:/vcprojects/images/dnn/bvlc_googlenet.caffemodel";
    
    //导入模型
    Net net = dnn::readNetFromCaffe(modelTxt, modelBin);
        if (net.empty())
        {
            std::cerr << "Can't load network by using the following files: " << std::endl;
            std::cerr << "prototxt:   " << modelTxt << std::endl;
            std::cerr << "caffemodel: " << modelBin << std::endl;
            return -1;
        }
        // 读取分类数据
        vector<String> labels = readClasslabels();
        //GoogLeNet accepts only 224x224 RGB-images
        Mat inputBlob = blobFromImage(testImage, 1, Size(224, 224), Scalar(104, 117, 123)); 

    3. 读取图像分类索引与文本描述

    vector<String> readClasslabels() {
        std::vector<String> classNames;
        std::ifstream fp(labelFile);
        if (!fp.is_open())
        {
            std::cerr << "File with classes labels not found: " << labelFile << std::endl;
            exit(-1);
        }
        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;
    }

    效果:

  • 完整代码链接

猜你喜欢

转载自blog.csdn.net/red_ear/article/details/85990162