Repository navigation
Expand file tree
/
Copy pathscale_obj.py
More file actions
71 lines (58 loc) · 2.51 KB
/
Copy pathscale_obj.py
File metadata and controls
71 lines (58 loc) · 2.51 KB
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
import trimesh
import numpy as np
import os
import sys
def scale_mesh_uniformly(source_path, target_path, output_path):
"""
Scale the source mesh uniformly to match the approximate size of the target mesh
"""
# Load meshes
print("Loading source mesh: {}".format(source_path))
source_mesh = trimesh.load(source_path)
print("Loading target mesh: {}".format(target_path))
target_mesh = trimesh.load(target_path)
# Fix negative volume/inverted faces if needed
if source_mesh.volume < 0:
print("Source mesh has negative volume. Fixing normals...")
source_mesh.fix_normals()
if target_mesh.volume < 0:
print("Target mesh has negative volume. Fixing normals...")
target_mesh.fix_normals()
# Get dimensions
source_dim = source_mesh.bounds[1] - source_mesh.bounds[0]
target_dim = target_mesh.bounds[1] - target_mesh.bounds[0]
# Calculate individual scale factors
scale_factors = target_dim / np.maximum(source_dim, 1e-8)
print("Individual scale factors (XYZ): {:.6f}, {:.6f}, {:.6f}".format(
scale_factors[0], scale_factors[1], scale_factors[2]))
# Use the average for uniform scaling
uniform_scale = np.mean(scale_factors)
print("Using uniform scale factor: {:.6f}".format(uniform_scale))
# Apply the scaling transformation
matrix = np.eye(4)
matrix[:3, :3] *= uniform_scale
scaled_mesh = source_mesh.copy()
scaled_mesh.apply_transform(matrix)
# Check results
scaled_dim = scaled_mesh.bounds[1] - scaled_mesh.bounds[0]
print("\nResults:")
print("Original source dimensions: {:.4f} x {:.4f} x {:.4f}".format(
source_dim[0], source_dim[1], source_dim[2]))
print("Target dimensions: {:.4f} x {:.4f} x {:.4f}".format(
target_dim[0], target_dim[1], target_dim[2]))
print("Scaled dimensions: {:.4f} x {:.4f} x {:.4f}".format(
scaled_dim[0], scaled_dim[1], scaled_dim[2]))
# Save the scaled mesh
scaled_mesh.export(output_path)
print("Saved scaled mesh to: {}".format(output_path))
return scaled_mesh
if __name__ == "__main__":
if len(sys.argv) != 4:
print("Usage: python scale_obj.py [source_obj] [target_obj] [output_obj]")
print("\nExample:")
print("python scale_obj.py original.obj target_size.obj scaled_result.obj")
sys.exit(1)
source_path = sys.argv[1]
target_path = sys.argv[2]
output_path = sys.argv[3]
scale_mesh_uniformly(source_path, target_path, output_path)