如何使用幅度和absdiff OpenCV函数来计算距离?

时间:2016-05-27 21:43:44

标签: opencv opencv3.0

如何使用magnitudeabsdiff?我在the documentation中阅读了解释,但是每次它都会出错,因为我不明白究竟应该输入数组和输出。它应该是vectorMat还是Scalar?我尝试了一些,但我失败了,与cartToPolar相同。任何人都可以给我一小段内容,因为我在文档中没有找到任何例子?

更确切地说,我有向量vector<Vec4f> lines;,其中包含30行的终点和起点,所以我想使用幅度来查找每行的长度。我学习了如何使用norm for for循环,但我想使用magnitude所以我这样做:

double x;
length=magnitude(lines[i][2]-lines[i][0],lines[i][3]-lines[i][1],x)

但它不起作用。我试图将x定义为1个数组向量,但我不能。

1 个答案:

答案 0 :(得分:1)

您已经掌握了如何使用norm来计算距离:

Point2f a = ...
Point2f b = ..
double length = norm(a - b); // NORM_L2, NORM_L1

您也可以同时处理所有积分。首先需要将坐标从矢量转换为矩阵形式,然后它只是简单的数学运算:

#include <opencv2\opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;

int main() 
{
    vector<Vec4f> lines{ { 1, 2, 4, 6 }, { 5, 7, 1, 3 }, { 11, 12, 12, 11 } };

    Mat1f coordinates = Mat4f(lines).reshape(1);
    Mat1f diff_x = coordinates.col(0) - coordinates.col(2);
    Mat1f diff_y = coordinates.col(1) - coordinates.col(3);

    cout << "coordinates: \n" << coordinates << "\n\n";
    cout << "diff_x: \n" << diff_x << "\n\n";
    cout << "diff_y: \n" << diff_y << "\n\n";
    cout << endl;

    // sqrt((x2 - x1)^2 + (y2 - y1)^2)
    Mat1f euclidean_distance;
    magnitude(diff_x, diff_y, euclidean_distance);

    cout << "euclidean_distance: \n" << euclidean_distance << "\n\n";

    // abs(x2 - x1) + abs(y2 - y1)
    Mat1f manhattan_distance = abs(diff_x) + abs(diff_y);

    cout << "manhattan_distance: \n" << manhattan_distance << "\n\n";

    // Another way to compute L1 distance, with absdiff
    // abs(x2 - x1) + abs(y2 - y1)
    Mat1f points1 = coordinates(Range::all(), Range(0, 2));
    Mat1f points2 = coordinates(Range::all(), Range(2, 4));
    Mat1f other_manhattan_distance;
    absdiff(points1, points2, other_manhattan_distance);
    other_manhattan_distance = other_manhattan_distance.col(0) + other_manhattan_distance.col(1);

    cout << "other_manhattan_distance: \n" << other_manhattan_distance << "\n\n";

    return 0;
}