-
Notifications
You must be signed in to change notification settings - Fork 1
/
load_obj.py
93 lines (83 loc) · 3.24 KB
/
load_obj.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import cv2
import numpy as np
class objLoader:
def __init__(self, filename, filetexture=None, swapyz=False):
"""Loads a Wavefront OBJ file. """
self.vertices = []
self.normals = []
self.texcoords = []
self.texcoords_ = []
self.faces = []
if filetexture is not None:
self.texture = cv2.imread(filetexture)
material = None
for line in open(filename, "r"):
if line.startswith('#'): continue
values = line.split()
if not values: continue
if values[0] == 'v':
v = list(map(float, values[1:4]))
v = v[0], v[1], v[2]
if swapyz:
v = v[0], v[2], v[1]
self.vertices.append(v)
elif values[0] == 'vn':
v = list(map(float, values[1:4]))
if swapyz:
v = v[0], v[2], v[1]
self.normals.append(v)
elif values[0] == 'vt':
self.texcoords.append(map(float, values[1:3]))
self.texcoords_.append([float(a) for a in values[1:3]])
#elif values[0] in ('usemtl', 'usemat'):
#material = values[1]
#elif values[0] == 'mtllib':
#self.mtl = MTL(values[1])
elif values[0] == 'f':
face = []
texcoords = []
norms = []
for v in values[1:]:
w = v.split('/')
face.append(int(w[0]))
if len(w) >= 2 and len(w[1]) > 0:
texcoords.append(int(w[1]))
else:
texcoords.append(0)
if len(w) >= 3 and len(w[2]) > 0:
norms.append(int(w[2]))
else:
norms.append(0)
# self.faces.append((face, norms, texcoords, material))
# self.faces.append((face, norms, texcoords))
self.faces.append([face, norms, texcoords])
for f in self.faces:
if filetexture is not None:
f.append(self.decide_face_color(f[-1], self.texture, self.texcoords_))
else:
f.append((50, 50, 50)) #default color
def decide_face_color(self, hex_color, texture, textures):
#doesnt use proper texture
#takes the color at the mean of the texture coords
h, w, _ = texture.shape
col = np.zeros(3)
coord = np.zeros(2)
all_us = []
all_vs = []
for i in hex_color:
t = textures[i - 1]
coord = np.array([t[0], t[1]])
u , v = int(w*(t[0]) - 0.0001), int(h*(1-t[1])- 0.0001)
all_us.append(u)
all_vs.append(v)
u = int(sum(all_us)/len(all_us))
v = int(sum(all_vs)/len(all_vs))
# all_us.append(all_us[0])
# all_vs.append(all_vs[0])
# for i in range(len(all_us) - 1):
# texture = cv2.line(texture, (all_us[i], all_vs[i]), (all_us[i + 1], all_vs[i + 1]), (0,0,255), 2)
# pass
col = np.uint8(texture[v, u])
col = [int(a) for a in col]
col = tuple(col)
return (col)