In [5]:
from __future__ import division
import numpy as np
from numpy import *
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
In [6]:
class bresenham_diff:
'''
Bresenham's algorithm
Input: Takes starting point (p0) and endpoint (p1).
Output: set of pixel coordinates, or matrix with pixels filled in
TODO: add option to thicken lines, add option to gaussian blur
resource: http://floppsie.comp.glam.ac.uk/Glamorgan/gaius/gametools/6.html
see also: https://github.com/encukou/bresenham
but this is a actually WAY stripped down implementation purged of if-blocks
'''
def __init__(self, p0, p1):
self.initial = True
self.end = False
self.p0 = p0
self.p1 = p1
self.x0 = p0[0]
self.y0 = p0[1]
self.x1 = p1[0]
self.y1 = p1[1]
self.dx = abs(self.x1-self.x0)
self.dy = abs(self.y1-self.y0)
self.slope = self.dy/self.dx
self.sign = np.sign(self.slope)
self.xpix = []
self.ypix = []
self.imsize = 250
def walk_along(self):
'''
intuition: increment by x pixel, and fill in the closest y pixel as you go
'''
self.xpix = np.linspace(int(self.x0),int(self.x1),abs(self.dx)+1)
for _y in np.linspace(self.y0,self.y1,abs(self.dx)+1):
self.ypix.append(np.round(_y))
return self.xpix, self.ypix
def fillgrid(self,xpix,ypix):
mat = np.tile(0,(self.imsize,self.imsize))
for _x,_y in zip(xpix,ypix):
mat[int(_x),int(_y)] = 250
return mat
## add option to thicken lines
## add option to gaussian blur
In [7]:
start = [0,0]
end = [200,-180]
l = bresenham_diff(start,end)
xpix,ypix = l.walk_along()
mat = l.fillgrid(xpix,ypix)
In [9]:
sns.set_style('whitegrid')
plt.matshow(mat)
Out[9]:
In [ ]: