Skip to content

Instantly share code, notes, and snippets.

@wadoon
Created October 11, 2015 19:19
Show Gist options
  • Save wadoon/d4fc7ff6606b9b3c22d1 to your computer and use it in GitHub Desktop.
Save wadoon/d4fc7ff6606b9b3c22d1 to your computer and use it in GitHub Desktop.
Drawing barycentric coordinates with Python. n-edge polyon and a point is describes by 0 <= v_i <= 1, sum(v_i) = 1, 0 < i <= n
#!/usr/bin/python
from PIL import Image, ImageDraw
from math import cos, sin, pi,log
class BarycentricImage(object):
def __init__(self, n=3, size=(400,400)):
self.dims = n
self.size = size
self.image = Image.new("RGB", size, (255,255,255))
self.draw = ImageDraw.Draw(self.image)
self.draw.setink(0)
self.__draw_coordinates()
def __draw_coordinates(self):
self.coordinates = []
centerX, centerY = self.size[0]/2, self.size[1]/2
for alpha in range(self.dims):
r = (2*pi/self.dims)*alpha;
x = cos( r ) * self.size[0]/2.0 + centerX
y = sin( r ) * self.size[1]/2.0 + centerY
self.coordinates.append( (x,y) )
#print(self.coordinates)
self.draw.polygon(self.coordinates, (100,100,100), (50,50,50) )
def add_point(self, vector):
# assert len(vector) == self.dims
assert all(map(lambda x: 0 <= x <= 1, vector))
x,y = 0,0
s = sum(vector)
for v,(a,b) in zip(vector, self.coordinates):
x += v * a / s
y += v * b / s
print(x,y)
red = int(entropy(vector)/2.33*255)
self.draw.point( (x,y), (red,0,0))
def save(self, name):
del self.draw
self.image.save(name)
def entropy(seq):
def log0(x):
if x==0:
return 0
else:
return log(x,2)
return - sum(map(lambda p: p*log0(p), seq))
def prange(step=0.03):
i = 0
while i <= 1:
yield i
i += step
yield 1
if __name__ == "__main__":
I = BarycentricImage(5)
#b.add_point((0.5, 1, 0.5, 0.3, 0.6))
#b.add_point((0.2, 0.5, 0.5))
#b.add_point((0.6, 0.20, 0.35))
#b.add_point((0.7, 0.3, 0.35))
step = 0.01
for a in prange():
for b in prange():
for c in prange():
for d in prange():
for e in prange():
x = (a,b,c,d,e)
if sum(x) == 1:
I.add_point(x)
I.save("test.png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment