sorting points to form a continuous line

后端 未结 4 695
予麋鹿
予麋鹿 2020-12-13 02:37

I have a list of (x,y)-coordinates that represent a line skeleton. The list is obtained directly from a binary image:

import numpy as np    
list=np.where(im         


        
4条回答
  •  伪装坚强ぢ
    2020-12-13 03:16

    I am working on a similar problem, but it has an important constraint (much like the example given by the OP) which is that each pixel has either one or two neighboring pixel, in the 8-connected sense. With this constraint, there is a very simple solution.

    def sort_to_form_line(unsorted_list):
        """
        Given a list of neighboring points which forms a line, but in random order, 
        sort them to the correct order.
        IMPORTANT: Each point must be a neighbor (8-point sense) 
        to a least one other point!
        """
        sorted_list = [unsorted_list.pop(0)]
    
        while len(unsorted_list) > 0:
            i = 0
            while i < len(unsorted_list):
                if are_neighbours(sorted_list[0], unsorted_list[i]):
                    #neighbours at front of list
                    sorted_list.insert(0, unsorted_list.pop(i))
                elif are_neighbours(sorted_list[-1], unsorted_list[i]):
                    #neighbours at rear of list
                    sorted_list.append(unsorted_list.pop(i))
                else:
                    i = i+1
    
        return sorted_list
    
    def are_neighbours(pt1, pt2):
        """
        Check if pt1 and pt2 are neighbours, in the 8-point sense
        pt1 and pt2 has integer coordinates
        """
        return (np.abs(pt1[0]-pt2[0]) < 2) and (np.abs(pt1[1]-pt2[1]) < 2)
    

提交回复
热议问题