绘制拟合线(OpenCV)

Sun*_*nny 10 math geometry opencv

我正在使用OpenCV来拟合一组点中的一条线 cvFitLine()

cvFitLine()返回与线和线上的点共线的归一化向量.详情请见此处

使用此信息如何获取线的方程式以便我可以绘制线?

bra*_*jam 9

如果cvFitLine()返回归一化向量(vx,vy)和点(x0,y0),则该方程为

(x,y)=(x0,y0)+ t*(vx,vy)

其中,t从-∞到+∞运行.

这是你要求的,但可能不会立即有助于绘制线.您可能希望将其剪切到屏幕边界,或者可能是原始点集的边界框.要将线条剪切为矩形,只需求解t线条穿过矩形边界的值.


kar*_*thy 9

只需绘制一条大线而不是解决边界问题.例如:

cv.Line(img, (x0-m*vx[0], y0-m*vy[0]), (x0+m*vx[0], y0+m*vy[0]), (0,0,0))
Run Code Online (Sandbox Code Playgroud)

会这样做..对于m足够大:)


Hen*_*ndy 5

python这只是为任何路人阐明了 @brainjam 的答案。

使用单位向量(vx, vy)和线上某个点的直线公式(x0, y0)为:

(x, y) = (x0, y0) + t*(vx, vy)
Run Code Online (Sandbox Code Playgroud)

的回报cv2.fitLine()是:

np.array([vx, vy, x0, y0])
Run Code Online (Sandbox Code Playgroud)

在示例中,我有一条跨越图像高度的线,因此我想找到与和(顶部/底部边界)相交的t0和。t1y=0y=img.shape[0]

# get the fitLine for your set of points in the array, `line`
fit_line = cv2.fitLine(line, cv2.DIST_L2, 0, 0.01, 0.01)

# compute t0 for y=0 and t1 for y=img.shape[0]: (y-y0)/vy
t0 = (0-fit_line[3])/fit_line[1]
t1 = (img.shape[0]-fit_line[3])/fit_line[1]

# plug into the line formula to find the two endpoints, p0 and p1
# to plot, we need pixel locations so convert to int
p0 = (fit_line[2:4] + (t0 * fit_line[0:2])).astype(np.uint32)
p1 = (fit_line[2:4] + (t1 * fit_line[0:2])).astype(np.uint32)

# draw the line. For my version of opencv, it wants tuples so we
# flatten the arrays and convert
# args: cv2.line(image, p0, p1, color, thickness)
cv2.line(img, tuple(p0.ravel()), tuple(p1.ravel()), (0, 255, 0), 10)
Run Code Online (Sandbox Code Playgroud)