Extract Array of Coordinates from Line (C++ OpenCV)

青春壹個敷衍的年華 提交于 2019-12-18 08:57:18

问题


Using C++ / OpenCV I've drawn a line on an image using cv::line and now I'm trying to extract an array of its coordinates. I've tried assigning the line to cv::Mat but I get an error stating I cannot convert from void to cv::Mat. Is there a simple way to obtain these coordinates?

Thanks for the help!


回答1:


You have at least a couple of options. Assuming that you know the two endpoints A and Bof the line:

1) Draw the line with line(...) on an zero initialized mask of the same size of your image, and retrieve the points on the line (which will be the only white points on the mask) with findNonZero(...).

2) Use LineIterator to retrieve the points, without the need of drawing them nor creating a mask.

You need to store your points in a 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;
}



回答2:


You can see this answer. I presume this is what your question needs, Finding points in a line.

Opencv has Line Iterator function. Go through the documentation!

Here is a sample usage!

LineIterator it(img, pt1, pt2, 8);
for(int i = 0; i < it.count; i++, ++it)
{
    Point pt= it.pos(); 
   //Draw Some stuff using that Point pt
}


来源:https://stackoverflow.com/questions/31799518/extract-array-of-coordinates-from-line-c-opencv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!