Finding closest non-black pixel in an image fast

前端 未结 9 1851
青春惊慌失措
青春惊慌失措 2020-12-16 21:22

I have a 2D image randomly and sparsely scattered with pixels.
given a point on the image, I need to find the distance to the closest pixel that is not in the background

9条回答
  •  忘掉有多难
    2020-12-16 22:05

    Ok, this sounds interesting. I made a c++ version of a soulution, I don't know if this helps you. I think it works fast enough as it's almost instant on a 800*600 matrix. If you have any questions just ask.

    Sorry for any mistakes I've made, it's a 10min code... This is a iterative version (I was planing on making a recursive one too, but I've changed my mind). The algorithm could be improved by not adding any point to the points array that is to a larger distance from the starting point then the min_dist, but this involves calculating for each pixel (despite it's color) the distance from the starting point.

    Hope that helps

    //(c++ version)
    #include
    #include
    #include
    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

提交回复
热议问题