Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To transform a Shapely polygon into a numpy pixel array that represents a mask array in Python, you can follow these steps:

  1. Create a rasterization function that takes a Shapely polygon and returns a numpy pixel array.
import numpy as np from PIL import Image, ImageDraw from shapely.geometry import Polygon def rasterize_polygon(polygon, width, height): img = Image.new('L', (width, height), 0) draw = ImageDraw.Draw(img) xy = np.array(polygon.exterior.coords.xy).T xy[:, 1] = height - xy[:, 1] xy = tuple(map(tuple, xy)) draw.polygon(xy=xy, outline=1, fill=1) return np.array(img).astype(bool) 
  1. Create a numpy array of zeros with the width and height of the image you want.
width = 100 height = 100 mask = np.zeros((height, width), dtype=bool) 
  1. Define your polygon using Shapely.
polygon = Polygon([(25, 25), (75, 25), (75, 75), (25, 75)]) 
  1. Rasterize the polygon using the rasterization function and add it to the mask array.
polygon_mask = rasterize_polygon(polygon, width, height) mask = np.logical_or(mask, polygon_mask) 
  1. The final mask array can be used for further processing or saving as an image.
Image.fromarray(mask.astype(np.uint8)*255).show()