Skip to content

Instantly share code, notes, and snippets.

@Red-Eyed
Created November 24, 2018 19:40
Show Gist options
  • Save Red-Eyed/0b7ef3458c2878e0c2a95e1e4dfe67a7 to your computer and use it in GitHub Desktop.
Save Red-Eyed/0b7ef3458c2878e0c2a95e1e4dfe67a7 to your computer and use it in GitHub Desktop.
How to fix invalida polygons in shapely
from shapely.geometry import Polygon, MultiPolygon
from shapely.ops import polygonize
import numpy as np
from skimage import draw, io
img = np.zeros(shape=(600, 600, 3), dtype=np.uint8)
coords = np.array([[20, 20], [20, 400], [400, 20], [400, 400]], dtype=np.int32)
p = Polygon(coords)
rr, cc = draw.polygon_perimeter(np.int32(p.exterior.coords[:])[:, 0],
np.int32(p.exterior.coords[:])[:, 1])
img[rr, cc] = [255, 0, 255]
io.imshow(img)
io.show()
print(f"{type(p)} {p.is_valid}")
print(f"{type(p)} {p.is_empty}")
print(f"{type(p)} {p.is_closed}")
print(f"{type(p)} {p.is_simple}")
print(f"{type(p)} {p.area}")
print()
p = p.exterior
p = p.intersection(p)
p = polygonize(p)
p = MultiPolygon(p)
print(f"{type(p)} {p.is_valid}")
print(f"{type(p)} {p.is_empty}")
print(f"{type(p)} {p.is_closed}")
print(f"{type(p)} {p.is_simple}")
print(f"{type(p)} {p.area}")
print()
for p in p:
img[:] = 0
rr, cc = draw.polygon_perimeter(np.int32(p.exterior.coords[:])[:, 0], np.int32(p.exterior.coords[:])[:, 1])
img[rr, cc] = [255, 0, 255]
io.imshow(img)
io.show()
print(f"{type(p)} {p.is_valid}")
print(f"{type(p)} {p.is_empty}")
print(f"{type(p)} {p.is_closed}")
print(f"{type(p)} {p.is_simple}")
print(f"{type(p)} {p.area}")
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment