How to draw a rounded edges for a polygon having its x,y coordinates?

Viewed 233

I need to draw polygon from X, Y coordinates but with rounded corners I have the points of X, Y

My code is below, however if there is another library, I can use it.

Here my output image:

Test image

and this is the code

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)
1 Answers

You can do it by using the Pillow's ImageDraw module by first using the coordinates to draw a polygon and then outlining it with a wide line with rounded corners.

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()

Here's a 3X enlargement showing the polygon without the outline on the left, and with it drawn on the right. The effect is a little hard to see at such relatively low image resolutions.

screenshot show effect of drawing outline

Related