2017-10-06 33 views
1

我有一組(X,Y)座標光柵化從草圖:用PIL繪製圖像的更快方式?

x = [167, 109, 80, 69, 58, 31] 
y = [140, 194, 227, 232, 229, 229] 

我想重新創建草圖,並將其保存爲圖像。目前我使用PIL平局線功能,像這樣:

from PIL import Image, ImageDraw 
img = [[1, 1]] 
im = Image.new('L', (256, 256), 255) 
imgdata = np.array(img[0][1])*256 + np.array(img[0][1]) 
draw = ImageDraw.Draw(im) 
for i in range(len(x)-1): 
    draw.line((x[i],y[i], x[i+1], y[i+1]),fill=0,width=2) 
im.save('test.png') 

output

我不知道是否有一個更快的方法來做到這一點。 (x,y)點是按照繪圖順序排列的,因此可能使用Image.putdata()可以提供幫助嗎?

+0

'Image.putdata()'會要求你通過一些其他手段來創建像素數據,然後將它塞進一個'Image'對象,你想要做的,除非我懷疑你可以找到一些現有的模塊來做到這一點(畫線)。你正在用PIL做到最快的方式。 – martineau

+1

但是注意['ImageDraw.line()'](http://pillow.readthedocs.io/en/4.3.x/reference/ImageDraw.html#PIL.ImageDraw.PIL.ImageDraw.ImageDraw.line)將接受在一次調用中調用座標,所以你可以移除'for'循環並獲得至少一些速度提升。 – martineau

+1

擺脫'for'循環並嘗試使用一個'draw.line(* zip(x,y),fill = 0,width = 2)'調用。 – martineau

回答

1

這更多或更少的證明就是我在對能夠只使用一個電話繪製全線draw.line()評論(SAN的*前綴的zip()呼叫)的暗示。

它的好處是它需要更少的代碼,並且可能會更快(即使測試數據並不明顯)略快

import numpy as np 
from PIL import Image, ImageDraw 

img = [[1, 1]] 
x = [167, 109, 80, 69, 58, 31] 
y = [140, 194, 227, 232, 229, 229] 

im = Image.new('L', (256, 256), 255) 
imgdata = np.array(img[0][1])*256 + np.array(img[0][1]) 
draw = ImageDraw.Draw(im) 

#for i in range(len(x)-1): 
# draw.line((x[i],y[i], x[i+1], y[i+1]),fill=0,width=2) 

draw.line(zip(x, y), fill=0, width=2) # Draws entire line. 
#im.save('test.png') 
im.show() # Display the image. 

對於Python 3.x都有你需要更改使用zip()以下(其中,而這將是確定在Python 2做,將需要額外的線路,雖然無害,處理該是沒有必要的):

draw.line(list(zip(x, y)), fill=0, width=2) # Draws entire line.