Performance 快速查找图像中最近的非黑色像素

Performance 快速查找图像中最近的非黑色像素,performance,graphics,2d,pixel,Performance,Graphics,2d,Pixel,我有一张2D图像,随机地、稀疏地散布着像素。 给定图像上的一个点,我需要找到与背景色(黑色)以外的最近像素的距离。 最快的方法是什么 我能想到的唯一方法是为像素构建kd树。但我真的希望避免如此昂贵的预处理。而且,kd树似乎给了我比我需要的更多。我只需要距离的东西,我不在乎这是什么东西 搜索“最近邻搜索”,谷歌的前两个链接应该对你有所帮助 如果你只为每张图像做1个像素,我认为你最好的选择就是线性搜索,每次向外搜索1个像素宽的框。如果你的搜索框是正方形的,你就不能得到你找到的第一个点。你必须小心是的

我有一张2D图像,随机地、稀疏地散布着像素。
给定图像上的一个点,我需要找到与背景色(黑色)以外的最近像素的距离。
最快的方法是什么

我能想到的唯一方法是为像素构建kd树。但我真的希望避免如此昂贵的预处理。而且,kd树似乎给了我比我需要的更多。我只需要距离的东西,我不在乎这是什么东西

搜索“最近邻搜索”,谷歌的前两个链接应该对你有所帮助


如果你只为每张图像做1个像素,我认为你最好的选择就是线性搜索,每次向外搜索1个像素宽的框。如果你的搜索框是正方形的,你就不能得到你找到的第一个点。你必须小心

是的,最近邻搜索很好,但不能保证你会找到“最近的”。每次向外移动一个像素将产生一个正方形搜索-对角线将比水平/垂直方向更远。如果这很重要,您需要验证-继续展开,直到绝对水平距离大于“找到的”像素,然后计算所定位的所有非黑色像素上的距离。

您没有指定要如何测量距离。我将假设L1(直线),因为它更容易;可能这些想法可以修改为L2(欧几里德)

如果只对相对较少的像素执行此操作,则只需从源像素向外搜索螺旋,直到找到非黑色像素

如果你对很多/所有的像素都这样做,那么这样做如何:构建一个图像大小的二维数组,每个单元格存储到最近的非黑色像素的距离(如果需要,还存储该像素的坐标)。进行四次扫线:从左到右、从右到左、从下到上和从上到下。考虑左右扫掠;扫描时,保留一个一维列,其中包含在每行中看到的最后一个非黑色像素,并用到该像素的距离和/或坐标标记二维阵列中的每个单元。O(n^2)


或者,k-d树是过度杀戮;你可以用四叉树。只比我的行扫描代码难一点,内存多一点(但不到两倍),可能更快

正如派罗所说,搜索从原点一次移出一个像素的正方形的周长(即一次增加两个像素的宽度和高度)。当点击非黑色像素时,计算距离(这是第一次昂贵的计算),然后继续向外搜索,直到框的宽度是到第一个找到点的距离的两倍(超出此范围的任何点都不可能比原始找到的像素更近)。保存在该零件中找到的所有非黑点,然后计算它们之间的距离,查看它们是否比原始点更近

在理想的查找中,您只需进行一次昂贵的距离计算

更新:因为您在这里计算像素到像素的距离(而不是任意精度的浮点位置),所以您可以通过使用预先计算的查找表(仅一个按宽度排列的高度)将距离作为x和y的函数,大大加快此算法的速度。一个100x100阵列基本上需要40K内存,并在原点周围覆盖200x200平方米,还可以省去为找到的每个彩色像素进行昂贵的距离计算(无论是毕达哥拉斯还是矩阵代数)的成本。这个数组甚至可以预先计算并作为资源嵌入到你的应用程序中,以节省你的初始计算时间(这可能是严重的过度使用)

更新2:还有一些方法可以优化搜索方形周长。您的搜索应该从与轴相交的四个点开始,并一次向拐角移动一个像素(您有8个移动的搜索点,这很容易使这一点变得更麻烦,具体取决于应用程序的要求)。一旦您找到一个彩色像素,就不需要继续朝向角点,因为其余的点都离原点更远

在第一个找到的像素之后,可以使用查找表进一步将所需的附加搜索区域限制到最小值,以确保每个搜索点都比找到的点更近(再次从轴开始,并在达到距离限制时停止)。如果您必须在飞行中计算每个距离,那么第二个优化可能会非常昂贵


如果最近的像素在200x200框内(或任何适合您的数据的大小),您将只在像素限定的圆内搜索,只进行查找和比较。

我将为每个像素创建一个简单的查找表,预先计算到最近非黑色像素的距离,并将该值存储在与相应像素相同的偏移量中。当然,这样你需要更多的内存。

就我个人而言,我会忽略MusiGenesis关于查找表的建议

计算像素之间的距离并不昂贵,特别是对于这个初始测试,您不需要实际距离,因此不需要取平方根。您可以使用距离^2,即:

r^2 = dx^2 + dy^2
此外,如果一次向外移动一个像素,请记住:

(n + 1)^2 = n^2 + 2n + 1
或者,如果nx是当前值,而ox是上一个值:

    nx^2  = ox^2 + 2ox + 1
          = ox^2 + 2(nx - 1) + 1
          = ox^2 + 2nx - 1
=>  nx^2 += 2nx - 1 
很容易看出这是如何工作的:

1^2 =  0 + 2*1 - 1 =  1
2^2 =  1 + 2*2 - 1 =  4
3^2 =  4 + 2*3 - 1 =  9
4^2 =  9 + 2*4 - 1 = 16
5^2 = 16 + 2*5 - 1 = 25
etc...
因此,在每次迭代中,您只需要保留一些中间变量,因此:

int dx2 = 0, dy2, r2;
for (dx = 1; dx < w; ++dx) {  // ignoring bounds checks
   dx2 += (dx << 1) - 1;
   dy2 = 0;
   for (dy = 1; dy < h; ++dy) {
       dy2 += (dy << 1) - 1;
       r2 = dx2 + dy2;
       // do tests here
   }
}
intdx2=0,dy2,r2;
对于(dx=1;dxdx2+=(dx好的,听起来很有趣。
我制作了一个C++版本的灵魂,我不知道这是否能帮助你。我认为它的工作速度足够快,因为它几乎在800×600的瞬间。
//(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;
}
- (SomeBigObjCStruct *)nearestWalkablePoint:(SomeBigObjCStruct)point {    

typedef struct _testPoint { // using the IYMapPoint object here is very slow
    int x;
    int y;
} testPoint;

// see if the point supplied is walkable
testPoint centre;
centre.x = point.x;
centre.y = point.y;

NSMutableData *map = [self getWalkingMapDataForLevelId:point.levelId];

// check point for walkable (case radius = 0)
if(testThePoint(centre.x, centre.y, map) != 0) // bullseye
    return point;

// radius is the distance from the location of point. A square is checked on each iteration, radius units from point.
// The point with y=0 or x=0 distance is checked first, i.e. the centre of the side of the square. A cursor variable
// is used to move along the side of the square looking for a walkable point. This proceeds until a walkable point
// is found or the side is exhausted. Sides are checked until radius is exhausted at which point the search fails.
int radius = 1;

BOOL leftWithinMap = YES, rightWithinMap = YES, upWithinMap = YES, downWithinMap = YES;

testPoint leftCentre, upCentre, rightCentre, downCentre;
testPoint leftUp, leftDown, rightUp, rightDown;
testPoint upLeft, upRight, downLeft, downRight;

leftCentre = rightCentre = upCentre = downCentre = centre;

int foundX = -1;
int foundY = -1;

while(radius < 1000) {

    // radius increases. move centres outward
    if(leftWithinMap == YES) {

        leftCentre.x -= 1; // move left

        if(leftCentre.x < 0) {

            leftWithinMap = NO;
        }
    }

    if(rightWithinMap == YES) {

        rightCentre.x += 1; // move right

        if(!(rightCentre.x < kIYMapWidth)) {

            rightWithinMap = NO;
        }
    }

    if(upWithinMap == YES) {

        upCentre.y -= 1; // move up

        if(upCentre.y < 0) {

            upWithinMap = NO;
        }
    }

    if(downWithinMap == YES) {

        downCentre.y += 1; // move down

        if(!(downCentre.y < kIYMapHeight)) {

            downWithinMap = NO;
        }
    }

    // set up cursor values for checking along the sides of the square
    leftUp = leftDown = leftCentre;
    leftUp.y -= 1;
    leftDown.y += 1;
    rightUp = rightDown = rightCentre;
    rightUp.y -= 1;
    rightDown.y += 1;
    upRight = upLeft = upCentre;
    upRight.x += 1;
    upLeft.x -= 1;
    downRight = downLeft = downCentre;
    downRight.x += 1;
    downLeft.x -= 1;

    // check centres
    if(testThePoint(leftCentre.x, leftCentre.y, map) != 0) {

        foundX = leftCentre.x;
        foundY = leftCentre.y;
        break;
    }
    if(testThePoint(rightCentre.x, rightCentre.y, map) != 0) {

        foundX = rightCentre.x;
        foundY = rightCentre.y;
        break;
    }
    if(testThePoint(upCentre.x, upCentre.y, map) != 0) {

        foundX = upCentre.x;
        foundY = upCentre.y;
        break;
    }
    if(testThePoint(downCentre.x, downCentre.y, map) != 0) {

        foundX = downCentre.x;
        foundY = downCentre.y;
        break;
    }

    int i;

    for(i = 0; i < radius; i++) {

        if(leftWithinMap == YES) {
            // LEFT Side - stop short of top/bottom rows because up/down horizontal cursors check that line
            // if cursor position is within map
            if(i < radius - 1) {

                if(leftUp.y > 0) {
                    // check it
                    if(testThePoint(leftUp.x, leftUp.y, map) != 0) {
                        foundX = leftUp.x;
                        foundY = leftUp.y;
                        break;
                    }
                    leftUp.y -= 1; // moving up
                }
                if(leftDown.y < kIYMapHeight) {
                    // check it
                    if(testThePoint(leftDown.x, leftDown.y, map) != 0) {
                        foundX = leftDown.x;
                        foundY = leftDown.y;
                        break;
                    }
                    leftDown.y += 1; // moving down
                }
            }
        }

        if(rightWithinMap == YES) {
            // RIGHT Side
            if(i < radius - 1) {

                if(rightUp.y > 0) {

                    if(testThePoint(rightUp.x, rightUp.y, map) != 0) {
                        foundX = rightUp.x;
                        foundY = rightUp.y;
                        break;
                    }
                    rightUp.y -= 1; // moving up
                }
                if(rightDown.y < kIYMapHeight) {

                    if(testThePoint(rightDown.x, rightDown.y, map) != 0) {
                        foundX = rightDown.x;
                        foundY = rightDown.y;
                        break;
                    }
                    rightDown.y += 1; // moving down
                }
            }
        }

        if(upWithinMap == YES) {
            // UP Side
            if(upRight.x < kIYMapWidth) {

                if(testThePoint(upRight.x, upRight.y, map) != 0) {
                    foundX = upRight.x;
                    foundY = upRight.y;
                    break;
                }
                upRight.x += 1; // moving right
            }
            if(upLeft.x > 0) {

                if(testThePoint(upLeft.x, upLeft.y, map) != 0) {
                    foundX = upLeft.x;
                    foundY = upLeft.y;
                    break;
                }
                upLeft.y -= 1; // moving left
            }
        }

        if(downWithinMap == YES) {
            // DOWN Side
            if(downRight.x < kIYMapWidth) {

                if(testThePoint(downRight.x, downRight.y, map) != 0) {
                    foundX = downRight.x;
                    foundY = downRight.y;
                    break;
                }
                downRight.x += 1; // moving right
            }
            if(downLeft.x > 0) {

                if(testThePoint(upLeft.x, upLeft.y, map) != 0) {
                    foundX = downLeft.x;
                    foundY = downLeft.y;
                    break;
                }
                downLeft.y -= 1; // moving left
            }
        }
    }

    if(foundX != -1 && foundY != -1) {
        break;
    }

    radius++;
}

// build the return object
if(foundX != -1 && foundY != -1) {

    SomeBigObjCStruct *foundPoint = [SomeBigObjCStruct mapPointWithX:foundX Y:foundY levelId:point.levelId];
    foundPoint.z = [self zWithLevelId:point.levelId];
    return foundPoint;
}
return nil;