Created
November 13, 2019 07:51
-
-
Save poke1024/862bd06ffa39cd310a6a37245fb57191 to your computer and use it in GitHub Desktop.
create a bitmap mask from a shapely polygon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy | |
| import cairo | |
| def polygon_mask(polygon): | |
| assert polygon.geom_type == 'Polygon' | |
| minx, miny, maxx, maxy = polygon.bounds | |
| minx, miny = numpy.floor([minx, miny]).astype(numpy.int32) | |
| maxx, maxy = numpy.ceil([maxx, maxy]).astype(numpy.int32) | |
| w = int(maxx - minx) | |
| h = int(maxy - miny) | |
| pts = list(polygon.exterior.coords) - numpy.array([minx, miny]) | |
| with cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h) as surface: | |
| ctx = cairo.Context(surface) | |
| ctx.move_to(*pts[0]) | |
| for p in pts[1:]: | |
| ctx.line_to(*p) | |
| ctx.set_source_rgb(1, 1, 1) | |
| ctx.fill() | |
| surface.finish() | |
| data = numpy.ndarray( | |
| shape=(surface.get_height(), surface.get_stride() // 4), | |
| dtype=numpy.uint32, | |
| buffer=surface.get_data()) | |
| data = numpy.right_shift(data, 24).astype(numpy.uint8) | |
| return data > 0, (minx, miny, w, h) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment