好吧问题就是这样,
我知道函数Line()
,它在两点之间绘制线段.
我需要画线而不是线段,也使用线段的两个点.
[EN:根据之前发布的问题编辑,作为问题的答案]
我使用了你的解决方案,它在水平线上表现不错,但我在垂直线上仍然遇到问题.
例如,下面是使用点[306,411]和[304,8](紫色)和绘制线(红色)在600x600像素的图像上的示例.你有提示吗?
我知道这是一个非常古老的问题.我有完全相同的问题,我使用这个简单的代码:
double Slope(int x0, int y0, int x1, int y1){
return (double)(y1-y0)/(x1-x0);
}
void fullLine(cv::Mat *img, cv::Point a, cv::Point b, cv::Scalar color){
double slope = Slope(a.x, a.y, b.x, b.y);
Point p(0,0), q(img->cols,img->rows);
p.y = -(a.x - p.x) * slope + a.y;
q.y = -(b.x - q.x) * slope + b.y;
line(*img,p,q,color,1,8,0);
}
Run Code Online (Sandbox Code Playgroud)
首先,我计算线段的斜率,然后我将线段"延伸"到图像的边界.我计算线的新点,它位于x = 0和x = image.width.点本身可以在Image之外,这是一种讨厌的技巧,但解决方案非常简单.
您需要编写一个函数来为自己完成.我建议你把你的线放在ax + + + c = 0形式,然后将它与图像的4个边相交.请记住,如果您在[abc]形式中找到与另一条线相交的线,则只是两者的交叉积.图像的边缘将是
top_horizontal = [0 1 0];
left_vertical = [1 0 0];
bottom_horizontal = [0 1 -image.rows];
right_vertical = [1 0 -image.cols];
Run Code Online (Sandbox Code Playgroud)
此外,如果您对点之间的距离有所了解,您也可以在每个方向上沿着线选择非常远的点,我不认为传递给Line()的点需要在图像上.
我遇到了同样的问题,发现2.4.X OpenCV 上有一个已知错误,已针对新版本修复。
对于 2.4.X 版本,解决方案是在绘制线条之前使用以下命令剪裁线条cv::clipLine()
这里有一个我自己做的函数,在 2.4.13 OpenCV 上运行良好
void Detector::drawFullImageLine(cv::Mat& img, const std::pair<cv::Point, cv::Point>& points, cv::Scalar color)
{
//points of line segment
cv::Point p1 = points.first;
cv::Point p2 = points.second;
//points of line segment which extend the segment P1-P2 to
//the image borders.
cv::Point p,q;
//test if line is vertical, otherwise computes line equation
//y = ax + b
if (p2.x == p1.x)
{
p = cv::Point(p1.x, 0);
q = cv::Point(p1.x, img.rows);
}
else
{
double a = (double)(p2.y - p1.y) / (double) (p2.x - p1.x);
double b = p1.y - a*p1.x;
p = cv::Point(0, b);
q = cv::Point(img.rows, a*img.rows + b);
//clipline to the image borders. It prevents a known bug on OpenCV
//versions 2.4.X when drawing
cv::clipLine(cv::Size(img.rows, img.cols), p, q);
}
cv::line(img, p, q, color, 2);
}
Run Code Online (Sandbox Code Playgroud)