File size: 1,603 Bytes
8e314bc | 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 | def normalize_obj_custom(old_file, new_file):
vertices = []
other_lines = []
# Step 1: Read the OBJ file and extract vertices
with open(old_file, 'r') as file:
for line in file:
if line.startswith('v '): # Vertex line
parts = line.split()
vertices.append([float(parts[1]), float(parts[2]), float(parts[3])])
else:
other_lines.append(line) # Non-vertex lines
# Step 2: Find the min and max for each axis
min_x = min(vertex[0] for vertex in vertices)
max_x = max(vertex[0] for vertex in vertices)
min_y = min(vertex[1] for vertex in vertices)
max_y = max(vertex[1] for vertex in vertices)
min_z = min(vertex[2] for vertex in vertices)
max_z = max(vertex[2] for vertex in vertices)
# Step 3: Normalize x, y to [-1, 1] and z to [0, 2]
normalized_vertices = [
[
2 * ((vertex[0] - min_x) / (max_x - min_x)) - 1, # x to [-1, 1]
2 * ((vertex[1] - min_y) / (max_y - min_y)) - 1, # y to [-1, 1]
2 * ((vertex[2] - min_z) / (max_z - min_z)) # z to [0, 2]
]
for vertex in vertices
]
# Step 4: Write to the new OBJ file
with open(new_file, 'w') as file:
# Write normalized vertices
for vertex in normalized_vertices:
file.write(f"v {vertex[0]} {vertex[1]} {vertex[2]}\n")
# Write other lines (e.g., faces, normals, etc.)
file.writelines(other_lines)
# Example usage:
normalize_obj_custom('textured.obj', 'new.obj') |