This just spells out @brainjam's answer in python
for any passers by.
The formula for a line using a unit vector (vx, vy)
and some point on the line (x0, y0)
is:
(x, y) = (x0, y0) + t*(vx, vy)
The return from cv2.fitLine()
is:
np.array([vx, vy, x0, y0])
In the example case, I have a line spanning the height of my image, so I want to find the t0
and t1
that intersect with y=0
and y=img.shape[0]
(the top/bottom boundaries).
# 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)