VIKI-Assets / objects /bread /normalize_proportionally.py
FACEONG's picture
Upload folder using huggingface_hub
8e314bc verified
import numpy as np
def normalize_obj(input_file, output_file):
vertices = []
all_lines = []
# Read the OBJ file
with open(input_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])])
all_lines.append(line)
# Convert vertices to a numpy array for processing
vertices = np.array(vertices)
# Compute min and max for each axis
min_vals = np.min(vertices, axis=0)
max_vals = np.max(vertices, axis=0)
ranges = max_vals - min_vals
# Find the largest range between x and y
largest_range_xy = max(ranges[0], ranges[1])
# Normalize x and y to [-0.5, 0.5] and scale by the largest range
vertices[:, 0] = (vertices[:, 0] - (min_vals[0] + max_vals[0]) / 2) / largest_range_xy
vertices[:, 1] = (vertices[:, 1] - (min_vals[1] + max_vals[1]) / 2) / largest_range_xy
# Scale z proportionally to the largest xy range and shift it to start from 0
vertices[:, 2] = (vertices[:, 2] - min_vals[2]) / largest_range_xy
# Write the modified OBJ file
with open(output_file, 'w') as file:
count = 0
for line in all_lines:
if line.startswith('v '): # Replace vertex lines
vertex = vertices[count]
file.write(f"v {vertex[0]} {vertex[1]} {vertex[2]}\n")
count += 1
else:
file.write(line)
# Specify input and output files
input_file = 'old.obj'
output_file = 'new.obj'
# Normalize the OBJ file
normalize_obj(input_file, output_file)