错误概率——OpenCV图像分类

Wrong probability - OpenCV image classification

我正在尝试使用 OpenCV 学习图像分类,并从这个开始 tutorial/guide https://learnopencv.com/deep-learning-with-opencvs-dnn-module-a-definitive-guide/

为了测试一切正常,我从教程中下载了图像代码,一切正常,没有错误。我使用了与教程中完全相同的图像(老虎图片)。问题是他们得到了 91% 的匹配,而我只有 14%。

我的猜测是代码中缺少某些内容。因此,在指南中,同一程序的 python 版本使用 NumPy 来获取概率。但是我真的一点头绪都没有。

有问题的代码如下:

#include <iostream>
#include <fstream>
#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>
#include <opencv2/dnn/all_layers.hpp>

using namespace std;
using namespace cv;
using namespace dnn;

int main(int, char**) {
    vector<string> class_names;
    ifstream ifs(string("../data/classification_classes_ILSVRC2012.txt").c_str());
    string line;
    while (getline(ifs, line)){
        class_names.push_back(line);
    }
    auto model = readNet("../data/DenseNet_121.prototxt",
                         "../data/DenseNet_121.caffemodel",
                         "Caffe");

    Mat image = imread("../data/tiger.jpg");
    Mat blob = blobFromImage(image, 0.01, Size(224, 224), Scalar(104, 117, 123));
    model.setInput(blob);
    Mat outputs = model.forward();
    double final_prob;
    minMaxLoc(outputs.reshape(1, 1), nullptr, &final_prob, nullptr, &classIdPoint);

    cout << final_prob;
}

如果有人能帮助我,我将不胜感激!

引用自here

From these, we are extracting the highest label index and storing it in label_id. However, these scores are not actually probability scores. We need to get the softmax probabilities to know with what probability the model predicts the highest-scoring label.

In the Python code above, we are converting the scores to softmax probabilities using np.exp(final_outputs) / np.sum(np.exp(final_outputs)). Then we are multiplying the highest probability score with 100 to get the predicted score percentage.

确实,它的 c++ 版本不会这样做,但是如果您使用:

,您应该得到相同的数值结果
Mat outputs = model.forward();

Mat softmax;
cv::exp(outputs.reshape(1,1), softmax);
softmax /= cv::sum(softmax)[0];

double final_prob;
minMaxLoc(softmax, nullptr, &final_prob, nullptr, &classIdPoint);
final_prob *= 100;