opencv 版本 > 3.4 以上網絡
constexpr const char *image_path = "darknet.jpg";//待檢測圖片 constexpr const char *darknet_cfg = "darknet.cfg";//網絡文件 constexpr const char *darknet_weights = "darknet.weights";//訓練模型 const std::vector<std::string> class_labels = {"darknet","yolo"};//類標籤 void darknetDetection(const std::string &path,const std::string &darknet_cfg,const std::string &darknet_weights,std::vector<std::string> class_labels,float confidenceThreshold) { // 加載模型 cv::dnn::Net net = cv::dnn::readNetFromDarknet(darknet_cfg,darknet_weights); // 加載標籤集 std::vector<std::string> classLabels = class_labels; // 讀取待檢測圖片 cv::Mat img = cv::imread(path); cv::Mat blob = cv::dnn::blobFromImage(img,1.0/255.0,{416,416},0.00392,true); net.setInput(blob,"data"); // 檢測 cv::Mat detectionMat = net.forward("detection_out");// 6 845 1 W x H x C // 獲取網絡每層的用時並獲取總用時 std::vector<double> layersTimings; double freq = cv::getTickFrequency() / 1000; double time = net.getPerfProfile(layersTimings) / freq; std::ostringstream ss; ss << "detection time: " << time << " ms"; // 繪製總用時至原始圖片 cv::putText(img, ss.str(), cv::Point(20, 20), 0, 0.5, cv::Scalar(0, 0, 255)); // 遍歷全部結果集 for(int i = 0;i < detectionMat.rows;++i){ const int probability_index = 5; const int probability_size = detectionMat.cols - probability_index; float *prob_array_ptr = &detectionMat.at<float>(i, probability_index); size_t objectClass = std::max_element(prob_array_ptr, prob_array_ptr + probability_size) - prob_array_ptr; float confidence = detectionMat.at<float>(i, (int)objectClass + probability_index); // 比較置信度並繪製知足條件的置信度 if (confidence > confidenceThreshold) { float x = detectionMat.at<float>(i, 0); float y = detectionMat.at<float>(i, 1); float width = detectionMat.at<float>(i, 2); float height = detectionMat.at<float>(i, 3); int xLeftBottom = static_cast<int>((x - width / 2) * img.cols); int yLeftBottom = static_cast<int>((y - height / 2) * img.rows); int xRightTop = static_cast<int>((x + width / 2) * img.cols); int yRightTop = static_cast<int>((y + height / 2) * img.rows); cv::Rect object(xLeftBottom, yLeftBottom,xRightTop - xLeftBottom,yRightTop - yLeftBottom);//x y w h cv::rectangle(img, object, cv::Scalar(0, 0, 255), 2, 8); // 判斷類id是否符合標籤範圍並繪製該標籤,也就是矩陣的下標索引 if (objectClass < classLabels.size()) { cv::String label = cv::String(classLabels[objectClass]) + ": " + std::to_string(confidence); int baseLine = 0; cv::Size labelSize = cv::getTextSize(label,cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine); cv::rectangle(img, cv::Rect(cv::Point(xLeftBottom, yLeftBottom),cv::Size(labelSize.width, labelSize.height + baseLine)),cv::Scalar(255, 255, 255), cv::FILLED); cv::putText(img, label, cv::Point(xLeftBottom, yLeftBottom + labelSize.height),cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0)); } } } // 顯示圖片 cv::imshow("Darknet",img); cv::waitKey(0); }