如何使用Python PILLOW绘制虚线或点线的线条或矩形。 有人可以帮我吗?使用openCV我可以做到。但我想使用Pillow。
感谢@martineau的评论,我弄清了如何画虚线。这是我的代码。
cur_x = 0
cur_y = 0
image_width = 600
for x in range(cur_x, image_width, 4):
draw.line([(x, cur_y), (x + 2, cur_y)], fill=(170, 170, 170))
这会绘制一条灰色的虚线。
#!/usr/local/bin/python3
import numpy as np
from PIL import Image, ImageDraw
# Make empty black image
im = Image.new('L', (640,480))
# Draw white rectangle and ellipse
draw = ImageDraw.Draw(im)
draw.rectangle([20,20,620,460],outline=255)
draw.ellipse([100,100,540,380],outline=255)
# Make noisy overlay, 1/4 the size, threshold at 50%, scale up to full-size
noise = np.random.randint(0,256,(120,160),dtype=np.uint8)
noise = (noise>128)*255
noiseim = Image.fromarray(noise.astype(np.uint8))
noiseim = noiseim.resize((640,480), resample=Image.NEAREST)
# Paste the noise in, but only allowing the white shape outlines to be affected
im.paste(noiseim,mask=im)
im.save('result.png')
我知道这个问题有点老(在我写这篇答案时已经4年了),但恰好我需要画一个带图案的线。
所以我在这里想出了自己的解决方案:https://codereview.stackexchange.com/questions/281582/algorithm-to-traverse-a-path-through-several-data-points-and-draw-a-patterned-li
(抱歉,解决方案有点长,最好去那里看看。不过代码是可行的,这就是为什么它在CodeReview SE中的原因)。
提供正确的“模式字典”,其中空白段由将color
设置为None
来表示,然后你就可以开始了。
import math # math has the fastest sqrt
def linedashed(x0, y0, x1, y1, dashlen=4, ratio=3):
dx=x1-x0 # delta x
dy=y1-y0 # delta y
# check whether we can avoid sqrt
if dy==0: vlen=dx
elif dx==0: vlen=dy
else: vlen=math.sqrt(dx*dx+dy*dy) # length of line
xa=dx/vlen # x add for 1px line length
ya=dy/vlen # y add for 1px line length
step=dashlen*ratio # step to the next dash
a0=0
while a0<vlen:
a1=a0+dashlen
if a1>vlen: a1=vlen
draw.line((x0+xa*a0, y0+ya*a0, x0+xa*a1, y0+ya*a1), fill = (0,0,0))
a0+=step
len
来表示长度。这是一个内置函数名称。 - thoroc
pillow
不直接支持此功能。您可以编写自己的函数,使用ImageDraw.line()
来绘制多个短线段以模拟效果。另一个可能性是使用tkinter
模块,它支持虚线,进行绘图,然后将结果保存到 pillow 图像中——请参阅 如何将画布内容转换为图像? 了解如何实现。 - martineau