从直线中提取坐标数组 (C++ OpenCV)

MST*_*TTm 5 c++ arrays opencv line coordinates

使用 C++/OpenCV,我在图像上画了一条线cv::line,现在我正在尝试提取其坐标数组。我尝试将该行分配给cv::Mat,但收到一条错误消息,指出我无法从 void 转换为cv::Mat. 有没有简单的方法来获取这些坐标?

谢谢您的帮助!

Mik*_*iki 5

您至少有几个选择。假设您知道 直线的两个端点A和:B

1) 在与图像大小相同的零初始化蒙版上绘制线条line(...),并使用 检索线条上的点(这将是蒙版上唯一的白点)findNonZero(...)

2) 用于LineIterator检索点,无需绘制它们或创建遮罩。

您需要将您的积分存储在vector<Point>.

#include <opencv2/opencv.hpp>
#include <vector>

using namespace std;
using namespace cv;

int main(int, char** argv)
{
    Mat3b image(100,100); // Image will contain your original rgb image

    // Line endpoints:
    Point A(10,20);
    Point B(50,80);


    // Method: 1) Create a mask
    Mat1b mask(image.size(), uchar(0));
    line(mask, A, B, Scalar(255));

    vector<Point> points1;
    findNonZero(mask, points1);

    // Method: 2) Use LineIterator
    LineIterator lit(image, A, B);

    vector<Point> points2;
    points2.reserve(lit.count);
    for (int i = 0; i < lit.count; ++i, ++lit)
    {
        points2.push_back(lit.pos());
    }

    // points1 and points2 contains the same points now!

    return 0;
}
Run Code Online (Sandbox Code Playgroud)