【发布时间】:2015-09-06 22:53:48
【问题描述】:
我想找到点之间的距离小于3的点。例如,一些点如下, (220,221)(220,119)(220,220)(20,90)(220,222)。 我用 (220,221) 来找点。然后我可以得到 (220,221)(220,119)(220,220)(220,222) 我使用 (220,119) 来查找点。然后我可以得到 (220,221)(220,119)(220,220) 我已经使用嵌套的for循环来做到这一点,但它很慢。它工作效率低下。代码如下,
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
using namespace std;
int main()
{
vector<Point> p;
vector<Point> temp;
vector<vector<Point> > centerbox;
p.push_back(Point(110, 110));
p.push_back(Point(110, 111));
p.push_back(Point(110, 110));
p.push_back(Point(110, 112));
p.push_back(Point(111, 112));
p.push_back(Point(150, 111));
for (vector<Point> ::iterator iter1 = p.begin(); iter1 != p.end(); ++iter1) {
for (vector<Point> ::iterator iter2 = p.begin(); iter2 != p.end();) {
if (abs((*iter1).x - (*iter2).x) + abs((*iter1).y - (*iter2).y) < 3) {
temp.push_back((*iter2));
++iter2;
}
else {
++iter2;
}
}
centerbox.push_back(temp);
temp.clear();
}
return 0;
}
我怎样做才能比使用嵌套 for 循环更快?
【问题讨论】:
-
您可以使用空间分区/散列技术将您的点“分类”到垃圾箱中。之后,对于固定的最大距离,您只需将每个点与几个相邻 bin 中的点进行比较。
-
使其更快的最简单方法是使用对称性。如果 p1 的 dist
-
使用简单的索引而不是迭代器,如果你知道点数的上限,那么使用数组而不是向量。
-
使用
std::vector::reserve和std::vector::emplace应该会给你一些性能提升。 -
谢谢大家!我之前也想用sort,但是sort很费时间,不是吗?
标签: c++ opencv for-loop dictionary vector