import numpy as np
import matplotlib.pyplot as plt
import matplotlib.collections as mc

# generate some data to work with, remember, we want the z points at the center
# of each pixel, so...

x,y = np.mgrid[-1:1:128j,-1:1:128j]
dx = x[1,0] - x[0,0]
dy = y[0,1] - y[0,0]
z = np.sqrt((x[:-1,:-1]+dx/2.0)**2 + (y[:-1,:-1]+dy/2.0)**2)

level = 0.5

zbelow = z <= level
parts = []

for k in xrange(z.shape[0]):
    for l in xrange(z.shape[1]):
        zz = 1 + 2 + 4 + 8
        if zbelow[k,l]:
            if l != 0 and zbelow[k,l-1]:
                zz -= 1
            if l != z.shape[1]-2 and zbelow[k,l+1]:
                zz -= 2
            if k != 0 and zbelow[k-1,l]:
                zz -= 4
            if k != z.shape[0]-2 and zbelow[k+1,l]:
                zz -= 8
            if zz != 0:
                parts.append((zz,k,l))


fig = plt.figure()
ax = fig.add_subplot(111)
segs = []


for which, k, l in parts:
    if which & 1:
        segs.append(np.asarray([x[(k,k+1),l], y[(k,k+1),l]]).T)
    if which & 2:
        segs.append(np.asarray([x[(k,k+1),l+1], y[(k,k+1), l+1]]).T)
    if which & 4:
        segs.append(np.asarray([x[k,(l,l+1)], y[k,(l,l+1)]]).T)
    if which & 8:
        segs.append(np.asarray([x[k+1,(l,l+1)], y[k+1,(l,l+1)]]).T)

ax.add_collection(mc.LineCollection(segs, colors='k'))
ax.autoscale_view()
plt.show()








