首页 > 解决方案 > 如何为具有 x,y 坐标的多边形绘制圆边?

问题描述

我需要从 X、Y 坐标绘制多边形,但圆角我有 X、Y 的点

我的代码在下面,但是如果有另一个库,我可以使用它。

这是我的输出图像:

测试图像

这是代码

def create_mask(dirct,filename,alistofpoint,height,width):
    myimg = np.zeros((height,width), dtype = "uint8")
    po = np.array(alistofpoint, np.int32)
    myimg_mod=cv2.fillPoly(myimg, [po],(255,255))
    cv2.imwrite(dirct+"//"+filename, myimg_mod)

标签: pythonnumpydrawingpolygoncv2

解决方案


您可以通过使用PillowImageDraw模块来做到这一点,首先使用坐标绘制多边形,然后用圆角的宽线勾勒出它的轮廓。

from operator import itemgetter
from pathlib import Path
from PIL import Image, ImageDraw


def create_mask(directory, filename, alistofpoint, height, width):
    mask = Image.new('L', (width, height), color=0)
    draw = ImageDraw.Draw(mask)
    draw.polygon(points, fill=255, outline=255)
    draw.line(points, fill=255, width=5, joint='curve')
    mask.save(Path(directory)/filename)
    return mask


pad = 25
points = [(114, 197), (96, 77), (110, 42), (138, 56,), (166, 124), (166, 174), (154, 195)]
width = max(points, key=itemgetter(0))[0] + pad
height = max(points, key=itemgetter(1))[1] + pad

mask = create_mask('\.', 'output_image.png', points, height, width)
mask.show()

这是一个 3X 放大图,显示了左侧没有轮廓的多边形,右侧绘制了它。在如此相对较低的图像分辨率下,效果有点难以看到。

截图显示绘制轮廓的效果


推荐阅读