Search code examples
pythonpolygonrectanglesshapely

Create a list of rectangles from a flat list of coordinates in Shapely


This doesn't answer my question.

I have a list of coordinates where every 5 consecutive coordinates define the coordinates of a rectangle, e.g.,

mylist=[(0, 7),(4, 7),(4, 12),(0, 12),(0, 7),(7, 1),(10, 1),(10, 8),(7, 8),(7, 1),(4, 8),(10, 8),(10, 12), (4, 12),(4, 8),(0, 0),(7, 0),(7, 7),(0, 7),(0, 0)]

I want to create four rectangles in Shapely with these coordinates shown in the example. The four rectangles should also be uniquely identifiable. Also, the list size can be variable as there can be more or less than the current number of coordinates.

EDIT:

At this point, I have 4 lists:

[[(0, 7), (4, 7), (4, 12), (0, 12), (0, 7)],
 [(7, 1), (10, 1), (10, 8), (7, 8), (7, 1)],
 [(4, 8), (10, 8), (10, 12), (4, 12), (4, 8)],
 [(0, 0), (7, 0), (7, 7), (0, 7), (0, 0)]] 

Now my question is how to pass these 4 sets of coordinates to shapely so I can later draw them in a figure and identify them individually? I am new to shapely.


Solution

  • You could store your Shapely objects in a dictionary and use them whenever your want afterwards, as e.g. below:

    from shapely.geometry import Polygon
    
    your_list = [[(0, 7), (4, 7), (4, 12), (0, 12), (0, 7)],
                [(7, 1), (10, 1), (10, 8), (7, 8), (7, 1)],
                [(4, 8), (10, 8), (10, 12), (4, 12), (4, 8)],
                [(0, 0), (7, 0), (7, 7), (0, 7), (0, 0)]] 
    
    your_dict = {}
    
    for i,sublist in enumerate(your_list):
        
        your_dict[i] = Polygon(sublist)
    

    Then plot them you could use your_dict in this way:

    plt.figure()
    
    for key,your_polygon in your_dict.items():
        
        plt.plot(*your_polygon.exterior.xy)
    

    which would give:

    enter image description here