cv::dnn::NMSBoxes 的非dnn版本
时间: 2023-07-31 15:10:19 浏览: 197
用opencv的dnn模块实现人脸口罩检测包含C++和Python源码+模型+说明.zip
cv::dnn::NMSBoxes是OpenCV中深度学习模块(dnn)中提供的一种非极大值抑制(NMS)的函数,用于去除检测结果中的重复框。如果不使用OpenCV的深度学习模块,可以通过以下代码实现非dnn版本的NMSBoxes函数:
```
void NMSBoxes(const std::vector<cv::Rect>& boxes, const std::vector<float>& scores, float score_threshold, float nms_threshold, std::vector<int>& indices) {
// 将boxes和scores打包成一个结构体数组
struct BoxWithScore {
cv::Rect box;
float score;
};
std::vector<BoxWithScore> boxes_with_scores;
for (int i = 0; i < boxes.size(); i++) {
boxes_with_scores.push_back({ boxes[i], scores[i] });
}
// 按照得分从高到低排序
std::sort(boxes_with_scores.begin(), boxes_with_scores.end(), [](const BoxWithScore& a, const BoxWithScore& b) {
return a.score > b.score;
});
// 执行NMS
indices.clear();
for (int i = 0; i < boxes_with_scores.size(); i++) {
if (boxes_with_scores[i].score < score_threshold) {
break;
}
bool keep = true;
for (int j = 0; j < indices.size(); j++) {
if (keep) {
int overlap_area = (boxes_with_scores[i].box & boxes_with_scores[indices[j]].box).area();
int union_area = boxes_with_scores[i].box.area() + boxes_with_scores[indices[j]].box.area() - overlap_area;
keep = overlap_area * 1.0 / union_area <= nms_threshold;
}
else {
break;
}
}
if (keep) {
indices.push_back(i);
}
}
}
```
以上代码仅供参考,实际的实现可能会有所不同,具体实现方式可能因模型和框架而异。
阅读全文