0

I would like to extract straight lines from a 2D binary matrix.

256x128 matrix

I would to find 1s grouped by neighbor coordinates.
In the attached image, there is a 256x128 binary matrix.
4 straight lines can be extracted from the given example.
After finding all grouped 1s, I would like to have a vector [x1,y1,x2,y2] which contains 2 edge coordinates. In the given example, there should be 4 vectors of course.

There is no chance that they can cross themselves.
Matrix always contains shapes similar to straight lines.

Language does not matter, preferably Python code.
I tried to use numpy and scipy.spatial.distance libraries to create a solution but failed.

Which techniques I should use, or which libs/functions I should look into?
Thanks in advance.

lotdcotw
  • 21
  • 3

1 Answers1

1

I have found a solution.
scipy.ndimage.measurements.label is to group them by labels.
scipy.spatial for convex hull and furthest pairs.

labeled_array, num_features = label(data)  # group and label
vectors = []
for i in range(num_features):
    index = i + 1
    indices = np.argwhere(labeled_array == index)  # find the group
    if len(indices) < THRESHOLD:  # not an important line if under threshold
        continue
    candidates = indices[spatial.ConvexHull(indices).vertices]  # convex hull
    dist_mat = spatial.distance_matrix(candidates, candidates)  # distance btw
    points = np.unravel_index(dist_mat.argmax(), dist_mat.shape)  # furthest cands
    vectors.append([candidates[points[0]], candidates[points[1]]])

You can find a complete python file in my repository.
https://github.com/lotdcotw/ets2ap/blob/main/matrix2vector.py

lotdcotw
  • 21
  • 3