如何在opencv中找到图像内像素之间的欧氏距离

时间:2016-11-22 12:35:28

标签: c++ image opencv matrix

int main(){
    Mat cmp, Ref, Diff;
    cmp = imread("image1.tif", CV_LOAD_IMAGE_UNCHANGED);
    Ref = imread("image2.tif", CV_LOAD_IMAGE_UNCHANGED);
    ShiftChk(cmp, Ref);
    absdiff(cmp, Ref, Diff);
    imshow("difference image", Diff);
    waitKey(0);
    double min, max;
    minMaxLoc(Diff, &min, &max);
    Point min_loc, max_loc;
    minMaxLoc(Diff, &min, &max, &min_loc, &max_loc);
    Size sz = Diff.size();
    cout << "max val : " << max << endl;//5
    cout << "max val: " << max_loc << endl; //[26,38]


    vector<vector<double>>test;
    for (int i = 0; i < Diff.cols; i++) {
        for (int j = 0; j < Diff.rows; j++) {

            Point difference = Diff.at<uchar>(26, 38) - Diff.at<uchar>(j, i);
            double dist = sqrt(difference.x*difference.x + difference.y*difference.y);              
            test.push_back(dist);
        }
    }
}

我试图找到图像中单个点与所有其他像素之间的欧几里德距离。距离值将存储在矢量测试中,但它在其中显示一些错误。而且我也不知道我使用的逻辑是否正确以给出正确的答案(欧几里德距离)。谁能帮我吗。提前致谢

错误信息是:

error C2664: 
'void std::vector<std::vector<double,std::allocator<_Ty>>,std::allocator<std::vector<_Ty,std::allocator<_Ty>>>>::push_back(const std::vector<_Ty,std::allocator<_Ty>> &)' : 
cannot convert argument 1 from 'double' to 'std::vector<double,std::allocator<_Ty>> &&' 

2 个答案:

答案 0 :(得分:1)

有两个主要问题:

  1. 您将test向量的值附加错误。您需要创建一个中间向量,并将push_back创建为test(如@0X0nosugar answer所示),或者更好地使用正确的维度初始化向量并将值放在正确的位置。< / p>

    vector<vector<double>> test(Diff.rows, vector<double>(Diff.cols));
    for (int i = 0; i < Diff.rows; i++) {
        for (int j = 0; j < Diff.cols; j++) {
            test[i][j] = ...       
        }
    }
    

    如上面的代码段所示,按行扫描更好(也更快),因为OpenCV按行存储图像。

  2. 您没有计算两点之间的距离。实际上,您正在两个给定点处取值并创建一个Point对象(这没有意义)。此外,您可以避免明确计算欧氏距离。您可以使用cv::norm

     test[i][j] = norm(Point(38, 26) - Point(j, i)); // Pay attention to i,j order!
    
  3. 全部放在一起:

    Point ref(38, 26);
    vector<vector<double>> test(Diff.rows, vector<double>(Diff.cols));
    for (int i = 0; i < Diff.rows; i++) {
        for (int j = 0; j < Diff.cols; j++) {
            test[i][j] = norm(ref - Point(j,i));      
        }
    }
    

答案 1 :(得分:0)

您将test声明为vector持有vector<double>类型的元素。因此,test.push_back()只会使用vector<double>类型的参数。

您收到错误是因为您尝试将double变量 dist 作为参数传递。

为每列使用vector<double>来存储距离(英语距离公式看起来没问题),然后将其附加到测试

vector<vector<double>>test;
for (int i = 0; i < Diff.cols; i++) {
    vector<double> temp;
    for (int j = 0; j < Diff.rows; j++) {

        Point difference = Diff.at<uchar>(26, 38) - Diff.at<uchar>(j, i);
        double dist = sqrt(difference.x*difference.x + difference.y*difference.y);              
        temp.push_back(dist);
    }
    test.push_back(temp);
}