在Python PIL中以线粗绘制椭圆

在Python PIL中以线粗绘制椭圆,第1张

在Python PIL中以线粗绘制椭圆

我遇到了同样的问题,因此决定编写一个类似于您的助手功能。此功能在蒙版层上绘制两个黑白的同心椭圆,并通过蒙版将所需的轮廓颜色压印到原始图像上。为了获得更平滑的结果(抗锯齿),将以更高的分辨率绘制椭圆和蒙版。

带或不带抗锯齿的输出

白色椭圆为20像素宽,黑色椭圆为0.5像素宽。

from PIL import Image, ImageDrawdef draw_ellipse(image, bounds, width=1, outline='white', antialias=4):    """Improved ellipse drawing function, based on PIL.ImageDraw."""    # Use a single channel image (mode='L') as mask.    # The size of the mask can be increased relative to the imput image    # to get smoother looking results.     mask = Image.new(        size=[int(dim * antialias) for dim in image.size],        mode='L', color='black')    draw = ImageDraw.Draw(mask)    # draw outer shape in white (color) and inner shape in black (transparent)    for offset, fill in (width/-2.0, 'white'), (width/2.0, 'black'):        left, top = [(value + offset) * antialias for value in bounds[:2]]        right, bottom = [(value - offset) * antialias for value in bounds[2:]]        draw.ellipse([left, top, right, bottom], fill=fill)    # downsample the mask using PIL.Image.LANCZOS     # (a high-quality downsampling filter).    mask = mask.resize(image.size, Image.LANCZOS)    # paste outline color to input image through the mask    image.paste(outline, mask=mask)# green background imageimage = Image.new(mode='RGB', size=(700, 300), color='green')ellipse_box = [50, 50, 300, 250]# draw a thick white ellipse and a thin black ellipsedraw_ellipse(image, ellipse_box, width=20)# draw a thin black line, using higher antialias to preserve finer detaildraw_ellipse(image, ellipse_box, outline='black', width=.5, antialias=8)# Lets try without antialiasingellipse_box[0] += 350 ellipse_box[2] += 350draw_ellipse(image, ellipse_box, width=20, antialias=1)draw_ellipse(image, ellipse_box, outline='black', width=1, antialias=1)image.show()

我只在python 3.4中测试过此代码,但我认为它无需更改即可在2.7上运行。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5562395.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存