diff --git a/modules/dnn/src/layers/detection_output_layer.cpp b/modules/dnn/src/layers/detection_output_layer.cpp index 76142181ae..55ef36f95c 100644 --- a/modules/dnn/src/layers/detection_output_layer.cpp +++ b/modules/dnn/src/layers/detection_output_layer.cpp @@ -611,8 +611,13 @@ public: } } // Keep outputs k results per image. - std::sort(scoreIndexPairs.begin(), scoreIndexPairs.end(), - util::SortScorePairDescend >); + if ((_keepTopK * 8) > scoreIndexPairs.size()) { + std::sort(scoreIndexPairs.begin(), scoreIndexPairs.end(), + util::SortScorePairDescend >); + } else { + std::partial_sort(scoreIndexPairs.begin(), scoreIndexPairs.begin() + _keepTopK, scoreIndexPairs.end(), + util::SortScorePairDescend >); + } scoreIndexPairs.resize(_keepTopK); std::map > newIndices;