Created
October 3, 2018 14:32
-
-
Save psycharo-zz/f4e6bac05717dfc0bfca12f3d8952060 to your computer and use it in GitHub Desktop.
obj reader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def read_obj(fname, max_degree=6, dtype=np.float32): | |
''' | |
Reads a mesh from an obj file. | |
Faces are converted into triangles. | |
Arguments: | |
fname: path or file-like object | |
max_degree: maximum degree for the adjacency | |
dtype: type for the vertex array | |
Returns: | |
(verts, faces) | |
''' | |
if isinstance(fname, str): | |
fh = open(fname, 'r') | |
else: | |
fh = fname | |
verts, faces = [], [] | |
for line in fh.readlines(): | |
if line == '': | |
break | |
line = line.strip('\n').replace('\t', ' ') | |
values = line.split(' ') | |
if values[0] == 'v': | |
if len(values) != 4: | |
raise RuntimeError('only xyz are supported') | |
verts.append(list(map(float, values[1:]))) | |
elif values[0] == 'f': | |
idxs = list(map(lambda i: int(i)-1, values[1:])) | |
if len(idxs) == 3: | |
faces += [idxs] | |
elif len(values) == 5: | |
faces += [[idxs[0], idxs[1], idxs[2]], | |
[idxs[0], idxs[2], idxs[3]]] | |
else: | |
raise NotImplementedError() | |
if isinstance(fname, str): | |
fh.close() | |
return (np.array(verts, dtype=dtype), | |
np.array(faces, np.int64)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment