获得每次迭代的最大价值

时间:2017-08-10 11:36:47

标签: c++

我有一个cv::Mat mat,用它来做一些事情并得到一个std::vector<cv::Points> diagonalPoints用于进一步编码,这里很棘手 - 创建diagonalPoints之后我会浏览每一列以获得两点之间的最大距离(对于每列,因此我比较[i].x[i+1].x - 见下文)。但是(!)在计算之后我会得到每个 maxDist一列,这个列比prevoius高,而不是列的最大值

这是我的代码的重要部分:

for (int i = 0; i < diagonalPoints.size(); i++) {
    int dist = diagonalPoints[i + 1].y - diagonalPoints[i].y;

    if (diagonalPoints[i].x == diagonalPoints[i + 1].x) {
        if (dist > maxDist) {
            maxDist = dist;
            maxDistColumn = diagonalPoints[i].x;
            firstPt = diagonalPoints[i];
            secondPt = diagonalPoints[i + 1];
        }
    }
    else if (diagonalPoints[i].x != diagonalPoints[i + 1].x) {
        maxDist = 0;
    }
    std::cout << maxDist << " in i: " << maxDistColumn << "\n";
    farestPoints = std::make_pair(firstPt, secondPt);
    std::cout << farestPoints.first << ", " << farestPoints.second << " ";
}

输出是(减少它,仅用于第一列):

[0, 26], [0, 39] - maxDist: 13 in i: 0
[0, 26], [0, 39] - maxDist: 13 in i: 0
[0, 26], [0, 39] - maxDist: 13 in i: 0
[0, 42], [0, 950] - maxDist: 908 in i: 0
[0, 42], [0, 950] - maxDist: 908 in i: 0
[0, 42], [0, 950] - maxDist: 908 in i: 0

但我只想获得[0, 42], [0, 950] - maxDist: 908 in i: 0,因为这是最大的价值。当然,这可能只是我的代码中的一个简单的改变,但我真的没有得到它。我应该改变什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

我认为您只需要在找到列的末尾时将打印移动到该位置。

for (int i = 0; i < diagonalPoints.size() - 1 /* need to stop before going off the end */; i++) {
    if (diagonalPoints[i].x == diagonalPoints[i + 1].x) {
        // same column, so calculate distance and compare
        int dist = diagonalPoints[i + 1].y - diagonalPoints[i].y;
        if (dist > maxDist) {
            maxDist = dist;
            maxDistColumn = diagonalPoints[i].x;
            firstPt = diagonalPoints[i];
            secondPt = diagonalPoints[i + 1];
        }
    }
    else {
        // new column, so print the maximum and reset
        std::cout << maxDist << " in i: " << maxDistColumn << "\n";
        farestPoints = std::make_pair(firstPt, secondPt);
        std::cout << farestPoints.first << ", " << farestPoints.second << " ";
        maxDist = 0;
    }
}

// after the loop, we still have the last column to print
std::cout << maxDist << " in i: " << maxDistColumn << "\n";
farestPoints = std::make_pair(firstPt, secondPt);
std::cout << farestPoints.first << ", " << farestPoints.second << "