这个程序使用opencv dnn_objdetect模块加载一个caffe模型进行目标检测。输入的两张图片左边是飞机右边是公共汽车程序运行后会显示识别出来的图片cmd里也会输出一些信息以第一张图片为例解释一下cmd里的输出类别是飞机置信度是0.845box的左上角坐标是(41,116).右下角坐标是(415,254).代码#include opencv2/core_detect.hpp int main() { Mat img imread(cat.jpg); Net net readNetFromCaffe(SqueezeDet_deploy.prototxt, SqueezeDet.caffemodel); Mat original_img(img); imshow(src, img); resize(img, img, Size(416, 416)); Mat img_copy(img); img.convertTo(img, CV_32FC3); Mat input_blob blobFromImage(img, 1.0, Size(), Scalar(104, 117, 123), false); vectorMat outblobs(3); vectorString out_layers; out_layers.push_back(slice); out_layers.push_back(softmax); out_layers.push_back(sigmoid); vectorMat temp_blob; net.setInput(input_blob); net.forward(temp_blob, out_layers[0]); outblobs[0] temp_blob[2]; net.setInput(input_blob); outblobs[1] net.forward(out_layers[1]); net.setInput(input_blob); outblobs[2] net.forward(out_layers[2]); int delta_bbox_size[3] {23, 23, 36}; Mat delta_bbox(3, delta_bbox_size, CV_32F, outblobs[0].ptrfloat()); int class_scores_size[2] {4761, 20}; Mat class_scores(2, class_scores_size, CV_32F, outblobs[1].ptrfloat()); int conf_scores_size[3] {23, 23, 9}; Mat conf_scores(3, conf_scores_size, CV_32F, outblobs[2].ptrfloat()); InferBbox inf(delta_bbox, class_scores, conf_scores); inf.filter(0.7); float x_ratio (float)original_img.cols / img_copy.cols; float y_ratio (float)original_img.rows / img_copy.rows; for (size_t i 0; i inf.detections.size(); i) { int xmin inf.detections[i].xmin; int ymin inf.detections[i].ymin; int xmax inf.detections[i].xmax; int ymax inf.detections[i].ymax; String class_name inf.detections[i].label_name; cout Class: class_name \n Probability: inf.detections[i].class_prob\n Position: inf.detections[i].xmin inf.detections[i].ymin inf.detections[i].xmax inf.detections[i].ymax \n; rectangle(original_img, Point((int)(xmin * x_ratio), (int)(ymin * y_ratio)), Point((int)(xmax * x_ratio), (int)(ymax * y_ratio)), Scalar(0, 0, 255), 1); putText(original_img, class_name, Point((int)(xmin * x_ratio), (int)(ymin * y_ratio)),FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0, 0, 255), 1); } imshow(dst, original_img); waitKey(); }SqueezeDet_deploy.prototxt在opencv dnn_objdetect模块里有提供。SqueezeDet.caffemodel从下面这个链接里下载GitHub - opencv/opencv_3rdparty at dnn_objdetect_20170827 · GitHub这个模型可以检测的类别可以从这里获取https://raw.githubusercontent.com/opencv/opencv/3.4.0/samples/data/dnn/synset_words.txt