OpenCV, C++: Distance between two points

前端 未结 4 1734
旧时难觅i
旧时难觅i 2020-12-23 23:02

For a group project, we are attempting to make a game, where functions are executed whenever a player forms a set of specific hand gestures in front of a camera. To process

相关标签:
4条回答
  • 2020-12-23 23:21

    You should try this

    cv::Point a(1, 3);
    cv::Point b(5, 6);
    double res = cv::norm(a-b);//Euclidian distance
    
    0 讨论(0)
  • 2020-12-23 23:21

    Pythagoras is the fastest way, and it really isn't as expensive as you think. It used to be, because of the square-root. But modern processors can usually do this within a few cycles.

    If you really need speed, use OpenCL on the graphics card for image processing.

    0 讨论(0)
  • 2020-12-23 23:33

    As you correctly pointed out, there's an OpenCV function that does some of your work :)

    (Also check the other way)

    It is called magnitude() and it calculates the distance for you. And if you have a vector of more than 4 vectors to calculate distances, it will use SSE (i think) to make it faster.

    Now, the problem is that it only calculate the square of the powers, and you have to do by hand differences. (check the documentation). But if you do them also using OpenCV functions it should be fast.

    Mat pts1(nPts, 1, CV_8UC2), pts2(nPts, 1, CV_8UC2);
    // populate them
    Mat diffPts = pts1-pts2;
    Mat ptsx, ptsy;
    // split your points in x and y vectors. maybe separate them from start
    Mat dist;
    magnitude(ptsx, ptsy, dist); // voila!
    

    The other way is to use a very fast sqrt:

    // 15 times faster than the classical float sqrt. 
    // Reasonably accurate up to root(32500)
    // Source: http://supp.iar.com/FilesPublic/SUPPORT/000419/AN-G-002.pdf
    
    unsigned int root(unsigned int x){
        unsigned int a,b;
        b     = x;
        a = x = 0x3f;
        x     = b/x;
        a = x = (x+a)>>1;
        x     = b/x;
        a = x = (x+a)>>1;
        x     = b/x;
        x     = (x+a)>>1;
        return(x);  
    }
    
    0 讨论(0)
  • 2020-12-23 23:35

    This ought to a comment, but I haven't enough rep (50?) |-( so I post it as an answer.

    What the guys are trying to tell you in the comments of your questions is that if it's only about comparing distances, then you can simply use d=(dx*dx+dy*dy) = (x1-x2)(x1-x2) + (y1-y2)(y1-y2) thus avoiding the square root. But you can't of course skip the square elevation.

    0 讨论(0)
提交回复
热议问题