Skip to content

Instantly share code, notes, and snippets.

@VolkerH
Created July 20, 2021 15:13
Show Gist options
  • Save VolkerH/94d0e9499ec6cf34a00b63d122bacb7b to your computer and use it in GitHub Desktop.
Save VolkerH/94d0e9499ec6cf34a00b63d122bacb7b to your computer and use it in GitHub Desktop.
Napari to shapeley
import numpy as np
from shapely.geometry.polygon import Polygon
from shapely.geometry import GeometryCollection, LineString
def napari_shape_to_shapely(coords: np.ndarray, shape_type: str = "polygon"):
"""
Convert an individual napari shape from a shapes layer to a shapely object
There is no direct correspondence between a 'rectangle' in napari and a 'box' in
shapely. The command for creating a box only requires minimum and maximum x and y
coordinates, i.e. this is for axis aligned rectangles. In contrast, a napari rectangle
can be arbitrarily rotated and still be a rectangle.
So for converting a rectangle from napari to shapely we have to go to a polygon
"""
_coords = coords[:, ::-1].copy() # shapely has col,row order, numpy row,col
_coords[:, 1] *= -1 # axis direction flipped between shapely and napari
if shape_type in ("rectangle", "polygon", "ellipse"):
return Polygon(_coords)
elif shape_type in ("line", "path"):
return LineString(_coords)
else:
raise ValueError
def napari_shape_layer_to_shapely(s):
"""
Convert all shapes in a napari shape layer to shapely objects
and return a GeometryCollection
"""
shapes = []
for _coord, _st in zip(s.data, s.shape_type):
shapes.append(napari_shape_to_shapely(_coord, _st))
return GeometryCollection(shapes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment