Python.
I have a 2d list of the coordinates for the perimeter of a shape in the following format: [[x1, y1], [x2, y2], [x3, y3], ... ,[xn, yn]]
I want a function that will return the coordinates of the area enclosed by that perimeter.
Context: The perimeter coordinates are the coordinates enclosing a section of an image. The reason that I want the coordinates of the area is because I want to be able to highlight the full area of the section of the image when I plot it. Is there some python library and function that can efficiently do this?
I'm sure this can be done with a lot of for loops, but I'd rather use a more efficient way.
If I get it correctly, you either want a convex hull of those point coordinates, or a bounding box. So, check the following code and see which one suits you:
from shapely.geometry import Point, MultiPoint
test_coordinates = [[1,1], [2,5], [7, 4], [3, 6], [9, 1], [5,2]]
# create points for each 2D coordinates in the list:
point_coordinates = [Point(x[0], x[1]) for x in test_coordinates]
# create a single multipoint representation of all points:
multi_point = MultiPoint(point_coordinates)
# convex hull:
convex_hull = multi_point.convex_hull
# coordinates of the convex hull - see the output below / commented
print(convex_hull.exterior.coords.xy)
#Out[23]:
#(array('d', [1.0, 2.0, 3.0, 7.0, 9.0, 1.0]),
# array('d', [1.0, 5.0, 6.0, 4.0, 1.0, 1.0]))
# bounding box:
bounding_box = multi_point.bounds
print(bounding_box)
# (1.0, 1.0, 9.0, 6.0)
So, in the following figure, the coordinates are the blue points, convex hull is the red polygon and bounding box is the blue rectangle:
To create the plots, in case you want to see for your data:
import matplotlib.pyplot as plt
from shapely. Geometry import box
# plot points
plt.scatter([point.x for point in point_coordinates], [point.y for point in point_coordinates])
# plot convex hull
plt.plot(*convex_hull.exterior.xy, label='convex hull', color='red')
# plot bounding box
plt.plot(*box(*bounding_box, ccw=True).exterior.xy, label='bounding_box', color='green')
# show it all together!
plt.show()