Pillow库ImageDraw.polygon绘制出现扫描线伪影问题咨询
问题排查:Pillow ImageDraw.polygon扫描线伪影问题
问题背景
使用Pillow 9.1.0版本,调用ImageDraw.polygon填充多边形时出现扫描线伪影,但改用ImageDraw.line绘制同一路径轮廓显示正常,顶点数据已确认无误,问题仅在部分绘图场景触发。
代码示例:
img = Image.new("RGB", TARGETSIZE, (255,255,255)) img1 = ImageDraw.Draw(img) for p in paths: img1.polygon(p, fill = (0, 0, 0))
解决方案与排查方向
- 升级Pillow版本
9.1.0版本存在已知的多边形填充算法缺陷,后续版本(如9.5.0及以上)修复了大量绘图相关Bug,优先升级到最新稳定版:
pip install --upgrade pillow
- 检查顶点顺序
扫描线填充算法对顶点环绕方向(顺时针/逆时针)敏感,不规则的顶点顺序可能导致填充异常。统一调整顶点顺序为顺时针或逆时针:
def adjust_vertex_order(points): # 计算面积符号判断顶点方向 area = 0 n = len(points) for i in range(n): x1, y1 = points[i] x2, y2 = points[(i+1)%n] area += (x2 - x1) * (y2 + y1) # 逆时针则反转改为顺时针 if area < 0: return points[::-1] return points for p in paths: adjusted_p = adjust_vertex_order(p) img1.polygon(adjusted_p, fill=(0,0,0))
- 排查自交多边形
自交的多边形会干扰扫描线填充逻辑,用shapely库验证并修复:
from shapely.geometry import Polygon for p in paths: poly = Polygon(p) if not poly.is_simple: # 修复自交多边形 fixed_poly = poly.buffer(0) # 提取修复后的顶点(去除闭合重复点) fixed_points = list(fixed_poly.exterior.coords)[:-1] img1.polygon(fixed_points, fill=(0,0,0)) else: img1.polygon(p, fill=(0,0,0))
- 关闭抗锯齿
若绘图上下文默认开启抗锯齿,部分场景会与填充算法冲突,显式关闭:
img1 = ImageDraw.Draw(img) img1.polygon(p, fill=(0,0,0), antialias=False)
内容的提问来源于stack exchange,提问作者YellowButShort
相关产品推荐
相关产品推荐

