错误的概率-OpenCV图像分类



我正在尝试使用OpenCV学习图像分类,并已从本教程/指南开始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;
}

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

在此引用:

从中提取最高标签索引,并将其存储在label_id中。然而,这些分数实际上并不是概率分数。我们需要得到softmax概率,以了解模型预测最高得分标签的概率。

在上面的Python代码中,我们使用np.exp(final_outputs(/np.sum(np.exp(final_output((将分数转换为softmax概率。然后,我们将最高概率分数乘以100,得到预测的分数百分比。

事实上,它的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;

最新更新