opencv如何判断轮廓是直线还是曲线?
How to judge the contour is line or curve by opencv?
这张图片有两个轮廓。我可以用 opencv findcontour
函数找到两者。我想知道的是如何判断哪个轮廓是直线,哪个轮廓是曲线?谁能告诉我怎么做?
首先假设您有一条线,然后应用一些基本代数。
首先求直线的斜率和y轴截距。直线的斜率定义为 y 的变化除以 x 的变化。所以给定两个点 (x0,y0), (x1,y1):
slope = (y0-y1) / (x0-x1)
使用斜率截距方程 (y=mx+b)
并求解 b:
找到 y 截距
y = mx + b
b = y - mx
所以
y_intercept = y0 - slope * x0
一旦你有了斜率和 y 轴截距,你只需要遍历等高线的点,看看是否所有的点都落在同一条线上。如果他们这样做,你就有一条线;如果他们不这样做,你就有了曲线。
由于我不知道你使用的是什么语言,这里是伪代码的整个过程:
// First assume you have a line - find the slope and y-intercept
slope = (point[0].y - point[1].y) / (point[0].x - point[1].x);
y_intercept = point[0].y - (slope * point[0].x);
// Using slope-intercept (y = mx + b), see if the other points are on the same line
for (n = 0 to numPoints)
{
if ((slope * point[n].x + y_intercept) != point[n].y)
{
// You've found a point that's not on the line - as soon as you
// find a point that's not on the line, you know that the contour
// is not a straight line
}
}
请注意,您将在此处处理浮点数,因此您必须在 if
条件中考虑到这一点 - 您不能直接比较浮点数是否相等,所以你需要将它们四舍五入到某种可接受的准确度。为了使伪代码简单,我将其遗漏了。
迟到的回答但记录在案:
比较第一个点和最后一个点之间的距离与轮廓长度。
如果它们很接近,那么轮廓就是线状的,否则就是曲线。
这张图片有两个轮廓。我可以用 opencv findcontour
函数找到两者。我想知道的是如何判断哪个轮廓是直线,哪个轮廓是曲线?谁能告诉我怎么做?
首先假设您有一条线,然后应用一些基本代数。
首先求直线的斜率和y轴截距。直线的斜率定义为 y 的变化除以 x 的变化。所以给定两个点 (x0,y0), (x1,y1):
slope = (y0-y1) / (x0-x1)
使用斜率截距方程 (y=mx+b)
并求解 b:
y = mx + b
b = y - mx
所以
y_intercept = y0 - slope * x0
一旦你有了斜率和 y 轴截距,你只需要遍历等高线的点,看看是否所有的点都落在同一条线上。如果他们这样做,你就有一条线;如果他们不这样做,你就有了曲线。
由于我不知道你使用的是什么语言,这里是伪代码的整个过程:
// First assume you have a line - find the slope and y-intercept
slope = (point[0].y - point[1].y) / (point[0].x - point[1].x);
y_intercept = point[0].y - (slope * point[0].x);
// Using slope-intercept (y = mx + b), see if the other points are on the same line
for (n = 0 to numPoints)
{
if ((slope * point[n].x + y_intercept) != point[n].y)
{
// You've found a point that's not on the line - as soon as you
// find a point that's not on the line, you know that the contour
// is not a straight line
}
}
请注意,您将在此处处理浮点数,因此您必须在 if
条件中考虑到这一点 - 您不能直接比较浮点数是否相等,所以你需要将它们四舍五入到某种可接受的准确度。为了使伪代码简单,我将其遗漏了。
迟到的回答但记录在案:
比较第一个点和最后一个点之间的距离与轮廓长度。 如果它们很接近,那么轮廓就是线状的,否则就是曲线。