用宽线修复PIL.ImageDraw.Draw.line

问题描述 投票:2回答:2

从PIL文档:

PIL.ImageDraw.Draw.line(xy,fill = None,width = 0)

在xy列表中的坐标之间绘制一条线。

参数:

  • xy - 像[(x,y),(x,y),...]这样的2元组序列或像[x,y,x,y,...]这样的数值。
  • fill - 用于线条的颜色。
  • width - 行宽,以像素为单位。请注意,线连接处理不好,因此宽折线看起来不太好。

我正在寻找解决此问题的方法。对我来说一个很好的解决方案是让PIL.ImageDraw绘制的线具有圆形末端(capstyle中的TKinter)。在PIL.ImageDraw有相同的东西吗?

这就是我想要获得的:enter image description here

最小工作范例:

from PIL import Image, ImageDraw

WHITE = (255, 255, 255)
BLUE = "#0000ff"
MyImage = Image.new('RGB', (600, 400), WHITE)
MyDraw = ImageDraw.Draw(MyImage)

MyDraw.line([100,100,150,200], width=40, fill=BLUE)
MyDraw.line([150,200,300,100], width=40, fill=BLUE)
MyDraw.line([300,100,500,300], width=40, fill=BLUE)

MyImage.show()

MWE的结果:

enter image description here

python python-imaging-library pillow
2个回答
1
投票

我和你有同样的问题。但是,您可以通过简单地绘制与每个顶点处的线宽相同直径的圆来轻松解决问题。以下是您的代码,稍作修改,以解决问题

from PIL import Image, ImageDraw

WHITE = (255, 255, 255)
BLUE = "#0000ff"
RED  = "#ff0000"
MyImage = Image.new('RGB', (600, 400), WHITE)
MyDraw = ImageDraw.Draw(MyImage)

# Note: Odd line widths work better for this algorithm,
# even though the effect might not be noticeable at larger line widths

LineWidth = 41

MyDraw.line([100,100,150,200], width=LineWidth, fill=BLUE)
MyDraw.line([150,200,300,100], width=LineWidth, fill=BLUE)
MyDraw.line([300,100,500,300], width=LineWidth, fill=BLUE)

Offset = (LineWidth-1)/2

# I have plotted the connecting circles in red, to show them better
# Even though they look smaller than they should be, they are not.
# Look at the diameter of the circle and the diameter of the lines -
# they are the same!

MyDraw.ellipse ((150-Offset,200-Offset,150+Offset,200+Offset), fill=RED)
MyDraw.ellipse ((300-Offset,100-Offset,300+Offset,100+Offset), fill=RED)

MyImage.show()

Lines with rounded ends


2
投票

joint='curve'标准选项ImageDraw.line旨在解决它。

你的例子可能看起来像

from PIL import Image, ImageDraw

WHITE = (255, 255, 255)
BLUE = "#0000ff"
MyImage = Image.new('RGB', (600, 400), WHITE)
MyDraw = ImageDraw.Draw(MyImage)

line_points = [(100, 100), (150, 200), (300, 100), (500, 300)]
MyDraw.line(line_points, width=40, fill=BLUE, joint='curve')

MyImage.show()

解决端点需要特别小心,但关节是固定的。

结果:

Fixed line with joint='curve'

© www.soinside.com 2019 - 2024. All rights reserved.