我有一个随机和稀疏散布像素的2D图像。
给定图像上的一个点,我需要找到到不在背景色(黑色)中的最近像素的距离。
完成此操作的最快方法是什么?
我能想到的唯一方法是为像素构建kd-tree。但我真的想避免这种昂贵的预处理。而且,kd-tree似乎给了我更多的东西。我只需要到某个东西的距离,我不关心这个东西是什么。
发布于 2010-08-01 18:22:40
好的,这听起来很有趣。我做了一个c++版本的解决方案,我不知道这是否对你有帮助。我认为它的工作速度足够快,因为它在800*600矩阵上几乎是瞬间的。如果你有任何问题,尽管问。
很抱歉我犯了任何错误,这是一个10分钟的代码...这是一个迭代版本(我也打算做一个递归版本,但我改变了主意)。该算法可以通过不向点数组添加任何到起点的距离大于min_dist的点来改进,但这涉及到计算每个像素(尽管它的颜色)到起点的距离。
希望这能有所帮助
//(c++ version)
#include<iostream>
#include<cmath>
#include<ctime>
using namespace std;
//ITERATIVE VERSION
//picture witdh&height
#define width 800
#define height 600
//indexex
int i,j;
//initial point coordinates
int x,y;
//variables to work with the array
int p,u;
//minimum dist
double min_dist=2000000000;
//array for memorising the points added
struct point{
int x;
int y;
} points[width*height];
double dist;
bool viz[width][height];
// direction vectors, used for adding adjacent points in the "points" array.
int dx[8]={1,1,0,-1,-1,-1,0,1};
int dy[8]={0,1,1,1,0,-1,-1,-1};
int k,nX,nY;
//we will generate an image with white&black pixels (0&1)
bool image[width-1][height-1];
int main(){
srand(time(0));
//generate the random pic
for(i=1;i<=width-1;i++)
for(j=1;j<=height-1;j++)
if(rand()%10001<=9999) //9999/10000 chances of generating a black pixel
image[i][j]=0;
else image[i][j]=1;
//random coordinates for starting x&y
x=rand()%width;
y=rand()%height;
p=1;u=1;
points[1].x=x;
points[1].y=y;
while(p<=u){
for(k=0;k<=7;k++){
nX=points[p].x+dx[k];
nY=points[p].y+dy[k];
//nX&nY are the coordinates for the next point
//if we haven't added the point yet
//also check if the point is valid
if(nX>0&&nY>0&&nX<width&&nY<height)
if(viz[nX][nY] == 0 ){
//mark it as added
viz[nX][nY]=1;
//add it in the array
u++;
points[u].x=nX;
points[u].y=nY;
//if it's not black
if(image[nX][nY]!=0){
//calculate the distance
dist=(x-nX)*(x-nX) + (y-nY)*(y-nY);
dist=sqrt(dist);
//if the dist is shorter than the minimum, we save it
if(dist<min_dist)
min_dist=dist;
//you could save the coordinates of the point that has
//the minimum distance too, like sX=nX;, sY=nY;
}
}
}
p++;
}
cout<<"Minimum dist:"<<min_dist<<"\n";
return 0;
}https://stackoverflow.com/questions/307445
复制相似问题