SciPy Create 2D Polygon Mask

后端 未结 6 893
慢半拍i
慢半拍i 2020-11-29 19:07

I need to create a numpy 2D array which represents a binary mask of a polygon, using standard Python packages.

  • input: polygon vertices, image dimensions
  • <
6条回答
  •  无人及你
    2020-11-29 20:07

    You could try to use python's Image Library, PIL. First you initialize the canvas. Then you create a drawing object, and you start making lines. This is assuming that the polygon resides in R^2 and that the vertex list for the input are in the correct order.

    Input = [(x1, y1), (x2, y2), ..., (xn, yn)] , (width, height)

    from PIL import Image, ImageDraw
    
    img = Image.new('L', (width, height), 0)   # The Zero is to Specify Background Color
    draw = ImageDraw.Draw(img)
    
    for vertex in range(len(vertexlist)):
        startpoint = vertexlist[vertex]
        try: endpoint = vertexlist[vertex+1]
        except IndexError: endpoint = vertexlist[0] 
        # The exception means We have reached the end and need to complete the polygon
        draw.line((startpoint[0], startpoint[1], endpoint[0], endpoint[1]), fill=1)
    
    # If you want the result as a single list
    # You can make a two dimensional list or dictionary by iterating over the height and width variable
    list(img.getdata())
    
    # If you want the result as an actual Image
    img.save('polgon.jpg', 'JPEG')
    

    Is this what you were looking for, or were you asking something different?

提交回复
热议问题