File size: 1,718 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
42
43
44
45
46
47
48
49
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)