To transform a Shapely polygon into a numpy pixel array that represents a mask array in Python, you can follow these steps:
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)
width = 100 height = 100 mask = np.zeros((height, width), dtype=bool)
polygon = Polygon([(25, 25), (75, 25), (75, 75), (25, 75)])
polygon_mask = rasterize_polygon(polygon, width, height) mask = np.logical_or(mask, polygon_mask)
Image.fromarray(mask.astype(np.uint8)*255).show()
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
Asked: 2022-06-14 11:00:00 +0000
Seen: 7 times
Last updated: Aug 05 '21
How can popen() be used to direct streaming data to TAR?
In Python, can a string be utilized to retrieve a dataframe that has the same name as the string?
What is the method for merging field value and text into a singular line for display?
What is the method for programmatic access to a time series?