Skip to content

Instantly share code, notes, and snippets.

@Bahm
Created March 20, 2017 11:08
Show Gist options
  • Save Bahm/c444efc55e64f1d5e089a10a9b81e4d2 to your computer and use it in GitHub Desktop.
Save Bahm/c444efc55e64f1d5e089a10a9b81e4d2 to your computer and use it in GitHub Desktop.
Construct convex hull from image and output it as Phaser polygon (loadPolygon) for P2 physics engine.
#!/usr/bin/env python3
from PIL import Image
from scipy.spatial import ConvexHull
import numpy as np
img = Image.open('image.png')
alphas = list(img.split()[-1].getdata())
region = np.argwhere(alphas)
region = [r[0] for r in region]
allVertices = [(i % img.width, int(i / img.width)) for i in region]
hull = ConvexHull(allVertices)
hullVertices = [allVertices[i] for i in hull.vertices]
print("[{'shape': %s}]" % str(hullVertices).replace('(', '').replace(')', ''))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment