2017-07-18 306 views
1

從PIL文檔:修復PIL.ImageDraw.Draw.line與寬線

PIL.ImageDraw.Draw.line(XY,填充=無,寬度= 0)

繪製xy列表中的座標之間的一條線。

參數:

  • XY - 無論是2元組,例如[(X,Y),(X,Y),...]或數值等[X,Y,X,Y的順序,...]。
  • 填充 - 用於該線條的顏色。
  • width - 線寬,以像素爲單位。 請注意,線路連接處理不好,所以寬的多段線看起來不太好。

我正在尋找這個問題的修復程序。對我來說,一個好的解決方案是讓PIL.ImageDraw繪製的線條具有圓角(,位於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

回答

0

我有同樣的問題,因爲你。但是,只需繪製一個與每個頂點的線寬相同直徑的圓即可輕鬆解決問題。下面是你的代碼,稍加修改,來解決這個問題

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