Ask Your Question
2

What is the method to transform a Shapely polygon into a numpy pixel array that represents a mask array in Python?

asked 2022-06-14 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-08-05 11:00:00 +0000

djk gravatar image

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() 
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-14 11:00:00 +0000

Seen: 7 times

Last updated: Aug 05 '21