Skip to content

Instantly share code, notes, and snippets.

@zeffii
Forked from anonymous/3dgrid_downsample.py
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeffii/837abf502d39b32fe36f to your computer and use it in GitHub Desktop.
Save zeffii/837abf502d39b32fe36f to your computer and use it in GitHub Desktop.
from collections import defaultdict
def downsample(verts, n=(20,20,20)):
grid_3d = defaultdict(list)
bbox = getBBox(verts)
xdiv, ydiv, zdiv = get_divs(bbox)
def getBBox(verts):
rotated = list(zip(*verts[0][::-1]))
return [[min(dim), max(dim)] for dim in rotated]
def get_divs(bbox):
# refactor later.
x_span = bbox[0][1] - bbox[0][0]
y_span = bbox[1][1] - bbox[1][0]
z_span = bbox[2][1] - bbox[2][0]
x_seg = x_span / n[0]
y_seg = y_span / n[1]
z_seg = z_span / n[2]
xdiv = [bbox[0][0]+(x_seg*i) for i in range(n[0])]
ydiv = [bbox[1][0]+(y_seg*i) for i in range(n[1])]
zdiv = [bbox[2][0]+(z_seg*i) for i in range(n[2])]
return xdiv, ydiv, zdiv
def avg_vert(verts):
n_verts = len(verts)
if n_verts == 1:
return verts[0]
else:
s = verts[0]
[s += v for v in verts[1:]]
return s
def find_slot(dim, dimdivs):
for idx, div in reversed(list(enumerate(dimdivs))):
if not dim >= div:
continue
else:
return idx
return 0
def get_bucket_tuple(vec):
x_idx = find_slot(vec.x, xdiv)
y_idx = find_slot(vec.y, ydiv)
z_idx = find_slot(vec.z, zdiv)
return x_idx, y_idx, z_idx
for v in verts:
bucket = get_bucket_tuple(vec)
grid_3d[bucket].append(Vector(v))
return [avg_vert(v) for v in grid_3d.values()]
@enzyme69
Copy link

enzyme69 commented Jun 2, 2014

Is this for SN? I'll be patient and waited for the working script.

@ly29
Copy link

ly29 commented Jun 2, 2014

For find_slot I think python bisect or numpy.searchsorted is the right answer.
http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html
https://docs.python.org/3.4/library/bisect.html

Also return s*1/n_verts on line 34.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment