Linefit add-on

As a companion add-on to PlaneFit I put together a small add-on that can add a single edge (two connected vertices) that best fits a collection of selected vertices.
After installtion it will be available in the 3d-view menu Add → Fit line to selected and the result of applying it to a vaguely cylindrical point cloud is shown below:

Availability

As usual the add-on is available from my GitHub repository (right-click on the link and Save As ...)

Extra information

There are many ways to fit a line to a collection of points but here we use the same eigen decomposition we use for fitting a plane. Instead of selecting the eigen vector with the smallest eigen value as the normal of a plane, we now select the eigen vector with the largest eigen value. This vector accounts for most of the variance in the positions of all the vertices, and is therefore the best fit. (There are other metrics we could use and this explanation is may be a bit too much hand-waiving for real mathematicians but it works :-)
The relevant code is shown below:
import numpy as np

def lineFit(points):
    ctr = points.mean(axis=0)
    x = points - ctr
    M = np.cov(x.T)
    eigenvalues,eigenvectors = np.linalg.eig(M)
    direction = eigenvectors[:,eigenvalues.argmax()]
    return ctr,direction

No comments:

Post a Comment