I'm using the Python library Pillow to draw a polygon on an image. However, I've noticed that the points of the polygon are connected incorrectly. The result deviates from the expected order.
Here's an example code that illustrates the problem:
from PIL import Image, ImageDraw
points = [(1424.78029246002, 4532.803383681871),
(1266.061767906654, 4433.729671760151),
(1377.9552871320157, 4606.898085001197),
(1208.2906574370381, 4515.545919771916)]
image = Image.new("RGB", (1920, 1080), "white")
draw = ImageDraw.Draw(image)
draw.polygon(points, outline="red")
image.show()
The expected result would be a closed polygon with the points in the specified order: Point 1 -> Point 2 -> Point 3 -> Point 4. However, the points seem to be connected in a different order, resulting in an incorrect polygon.
I already tried the rearrange the points in multiple ways by sorting them by x or y, but it still did not work.
Is there a way to control the order of the points or adjust how Pillow draws polygons? Or is there any other solution to this problem?
Thank you in advance for your help!
The points are connected by ImageDraw.Draw.polygon()
in the order specified in the list, and then the last and first points are connected by another line. The points list you have given would be expected to give the double triangle shape you show in the linked image.
Here I've modified the point list to translate it to be within the 1920 by 1080 base image, as the points given are outside of that area.
from PIL import Image, ImageDraw
points = [(624, 532), #A
(466, 433), #B
(577, 606), #C
(408, 515)] #D
image = Image.new("RGB", (1920, 1080), "white")
draw = ImageDraw.Draw(image)
draw.polygon(points, outline="red")
image.show()
If you want a quadrilateral, reorder the last two points:
from PIL import Image, ImageDraw
points = [(624, 532), #A
(466, 433), #B
(408, 515), #D
(577, 606)] #C
image = Image.new("RGB", (1920, 1080), "white")
draw = ImageDraw.Draw(image)
draw.polygon(points, outline="red")
image.show()