You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pillow绘制多边形时顶点连接顺序错误问题求助

问题原因与解决方案

核心问题

你的顶点y坐标(4433~4606)远大于图像的高度(1080),所有顶点都在画布外部,导致你看到的只是线条在画布内的截断片段,误以为是Pillow打乱了连接顺序。实际上,draw.polygon()是严格按照传入的点顺序依次连接的(最后一个点会自动连回第一个点),不存在逻辑上的顺序错误。

解决方案

1. 调整顶点坐标到画布范围内

将所有点的坐标缩放或平移到图像的有效区域(x: 01919,y:01079)。例如缩小y坐标:

from PIL import Image, ImageDraw

# 缩放y坐标至画布范围内
points = [(1424.78, 4532.80/4),
          (1266.06, 4433.73/4),
          (1377.96, 4606.90/4),
          (1208.29, 4515.55/4)]

image = Image.new("RGB", (1920, 1080), "white")
draw = ImageDraw.Draw(image)
draw.polygon(points, outline="red", width=2)

image.show()

运行后就能看到按你指定顺序(Point1→Point2→Point3→Point4)绘制的闭合多边形。

2. 放大画布以容纳原始顶点

如果需要保留原始坐标,可根据顶点范围调整画布尺寸,并平移点到画布可视区域:

from PIL import Image, ImageDraw

points = [(1424.78029246002, 4532.803383681871),
          (1266.061767906654, 4433.729671760151),
          (1377.9552871320157, 4606.898085001197),
          (1208.2906574370381, 4515.545919771916)]

# 计算覆盖所有顶点的最小画布尺寸(加边距)
min_x, max_x = min(p[0] for p in points), max(p[0] for p in points)
min_y, max_y = min(p[1] for p in points), max(p[1] for p in points)
canvas_width = int(max_x - min_x) + 100
canvas_height = int(max_y - min_y) + 100

# 平移顶点,确保所有点在画布内
translated_points = [(x - min_x + 50, y - min_y + 50) for x, y in points]

image = Image.new("RGB", (canvas_width, canvas_height), "white")
draw = ImageDraw.Draw(image)
draw.polygon(translated_points, outline="red", width=2)

image.show()

补充说明

你之前尝试按x/y排序顶点无效,是因为问题本质不是顺序错误,而是坐标超出画布导致的视觉误解。Pillow完全遵循传入的点序列绘制,无需额外设置控制顺序的参数。

内容的提问来源于stack exchange,提问作者Niclas Trll

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 10:27:37