senngadaisuki commited on
Commit
dab1299
·
verified ·
1 Parent(s): 390d5b8

Upload 2 files

Browse files
Files changed (2) hide show
  1. rendering/LICENSE +201 -0
  2. rendering/blender_script.py +987 -0
rendering/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
rendering/blender_script.py ADDED
@@ -0,0 +1,987 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The Omni-Primitive-Transforms Authors
2
+ #
3
+ # This file is adapted from the Objaverse-XL rendering script
4
+ # (https://github.com/allenai/objaverse-xl/blob/main/scripts/rendering/blender_script.py),
5
+ # Copyright Allen Institute for AI, licensed under the Apache License, Version 2.0.
6
+ # The upstream script also incorporates code from OpenAI Point-E / Shap-E (MIT) and
7
+ # Zero-1-to-3 / stanford-shapenet-renderer, as noted in the docstrings below.
8
+ #
9
+ # Modifications: rotation-sequence rendering (72 views, 5-degree steps), segmentation-
10
+ # mask export as .npy, gray/black background handling, and a per-task resume loop.
11
+ #
12
+ # Licensed under the Apache License, Version 2.0 (the "License");
13
+ # you may not use this file except in compliance with the License.
14
+ # You may obtain a copy of the License at
15
+ #
16
+ # http://www.apache.org/licenses/LICENSE-2.0
17
+ #
18
+ # Unless required by applicable law or agreed to in writing, software
19
+ # distributed under the License is distributed on an "AS IS" BASIS,
20
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
+ # See the License for the specific language governing permissions and
22
+ # limitations under the License.
23
+
24
+ """Blender script to render images of 3D models."""
25
+ import argparse
26
+ import json
27
+ import math
28
+ import os
29
+ import random
30
+ import sys
31
+ from typing import Any, Callable, Dict, Generator, List, Literal, Optional, Set, Tuple
32
+
33
+ import bpy
34
+ import numpy as np
35
+ from mathutils import Matrix, Vector
36
+
37
+ IMPORT_FUNCTIONS: Dict[str, Callable] = {
38
+ "obj": bpy.ops.import_scene.obj,
39
+ # "glb": bpy.ops.import_scene.gltf,
40
+ # "gltf": bpy.ops.import_scene.gltf,
41
+ # "usd": bpy.ops.import_scene.usd,
42
+ # "fbx": bpy.ops.import_scene.fbx,
43
+ # "stl": bpy.ops.import_mesh.stl,
44
+ # "usda": bpy.ops.import_scene.usda,
45
+ # "dae": bpy.ops.wm.collada_import,
46
+ # "ply": bpy.ops.import_mesh.ply,
47
+ # "abc": bpy.ops.wm.alembic_import,
48
+ # "blend": bpy.ops.wm.append,
49
+ }
50
+
51
+
52
+ def set_camera(
53
+ radius: float = 1.8,
54
+ theta: float = 0, # radias 0 to 2 * pi
55
+ x: float = 0,
56
+ ) -> bpy.types.Object:
57
+ """Randomizes the camera location on a circle in the x,y plane and rotation towards the origin.
58
+
59
+ Args:
60
+ radius (float, optional): Radius of the circle in the x,y plane. Defaults to 2.0.
61
+ minz (float, optional): Minimum z value of the camera. Defaults to -2.2.
62
+ maxz (float, optional): Maximum z value of the camera. Defaults to 2.2.
63
+
64
+ Returns:
65
+ bpy.types.Object: The camera object.
66
+ """
67
+
68
+ # Calculate x and y coordinates on the circle
69
+ z = radius * np.cos(theta)
70
+ y = radius * np.sin(theta)
71
+
72
+ # Set the camera location
73
+ camera = bpy.data.objects["Camera"]
74
+ camera.location = Vector(np.array([x, y, z]))
75
+
76
+ # Camera looks towards the origin (0,0,0)
77
+ direction = -camera.location
78
+ rotation_euler = direction.to_track_quat("-Z", "Y").to_euler()
79
+ # rotation_euler = direction
80
+ camera.rotation_euler = rotation_euler
81
+
82
+ return camera
83
+
84
+
85
+ def _set_camera_at_size(i: int, scale: float = 1.5) -> bpy.types.Object:
86
+ """Debugging function to set the camera on the 6 faces of a cube.
87
+
88
+ Args:
89
+ i (int): Index of the face of the cube.
90
+ scale (float, optional): Scale of the cube. Defaults to 1.5.
91
+
92
+ Returns:
93
+ bpy.types.Object: The camera object.
94
+ """
95
+ if i == 0:
96
+ x, y, z = scale, 0, 0
97
+ elif i == 1:
98
+ x, y, z = -scale, 0, 0
99
+ elif i == 2:
100
+ x, y, z = 0, scale, 0
101
+ elif i == 3:
102
+ x, y, z = 0, -scale, 0
103
+ elif i == 4:
104
+ x, y, z = 0, 0, scale
105
+ elif i == 5:
106
+ x, y, z = 0, 0, -scale
107
+ else:
108
+ raise ValueError(f"Invalid index: i={i}, must be int in range [0, 5].")
109
+ camera = bpy.data.objects["Camera"]
110
+ camera.location = Vector(np.array([x, y, z]))
111
+ direction = -camera.location
112
+ rot_quat = direction.to_track_quat("-Z", "Y")
113
+ camera.rotation_euler = rot_quat.to_euler()
114
+ return camera
115
+
116
+
117
+ def _create_light(
118
+ name: str,
119
+ light_type: Literal["POINT", "SUN", "SPOT", "AREA"],
120
+ location: Tuple[float, float, float],
121
+ rotation: Tuple[float, float, float],
122
+ energy: float,
123
+ use_shadow: bool = False,
124
+ specular_factor: float = 1.0,
125
+ ):
126
+ """Creates a light object.
127
+
128
+ Args:
129
+ name (str): Name of the light object.
130
+ light_type (Literal["POINT", "SUN", "SPOT", "AREA"]): Type of the light.
131
+ location (Tuple[float, float, float]): Location of the light.
132
+ rotation (Tuple[float, float, float]): Rotation of the light.
133
+ energy (float): Energy of the light.
134
+ use_shadow (bool, optional): Whether to use shadows. Defaults to False.
135
+ specular_factor (float, optional): Specular factor of the light. Defaults to 1.0.
136
+
137
+ Returns:
138
+ bpy.types.Object: The light object.
139
+ """
140
+
141
+ light_data = bpy.data.lights.new(name=name, type=light_type)
142
+ light_object = bpy.data.objects.new(name, light_data)
143
+ bpy.context.collection.objects.link(light_object)
144
+ light_object.location = location
145
+ light_object.rotation_euler = rotation
146
+ light_data.use_shadow = use_shadow
147
+ light_data.specular_factor = specular_factor
148
+ light_data.energy = energy
149
+ return light_object
150
+
151
+
152
+ def randomize_lighting() -> Dict[str, bpy.types.Object]:
153
+ """Randomizes the lighting in the scene.
154
+
155
+ Returns:
156
+ Dict[str, bpy.types.Object]: Dictionary of the lights in the scene. The keys are
157
+ "key_light", "fill_light", "rim_light", and "bottom_light".
158
+ """
159
+
160
+ # Clear existing lights
161
+ bpy.ops.object.select_all(action="DESELECT")
162
+ bpy.ops.object.select_by_type(type="LIGHT")
163
+ bpy.ops.object.delete()
164
+
165
+ # Create key light
166
+ key_light = _create_light(
167
+ name="Key_Light",
168
+ light_type="SUN",
169
+ location=(0, 0, 0),
170
+ rotation=(0.785398, 0, -0.785398),
171
+ energy=random.choice([3, 4, 5]),
172
+ )
173
+
174
+ # Create fill light
175
+ fill_light = _create_light(
176
+ name="Fill_Light",
177
+ light_type="SUN",
178
+ location=(0, 0, 0),
179
+ rotation=(0.785398, 0, 2.35619),
180
+ energy=random.choice([2, 3, 4]),
181
+ )
182
+
183
+ # Create rim light
184
+ rim_light = _create_light(
185
+ name="Rim_Light",
186
+ light_type="SUN",
187
+ location=(0, 0, 0),
188
+ rotation=(-0.785398, 0, -3.92699),
189
+ energy=random.choice([3, 4, 5]),
190
+ )
191
+
192
+ # Create bottom light
193
+ bottom_light = _create_light(
194
+ name="Bottom_Light",
195
+ light_type="SUN",
196
+ location=(0, 0, 0),
197
+ rotation=(3.14159, 0, 0),
198
+ energy=random.choice([1, 2, 3]),
199
+ )
200
+
201
+ return dict(
202
+ key_light=key_light,
203
+ fill_light=fill_light,
204
+ rim_light=rim_light,
205
+ bottom_light=bottom_light,
206
+ )
207
+
208
+
209
+ def reset_scene() -> None:
210
+ """Resets the scene to a clean state.
211
+
212
+ Returns:
213
+ None
214
+ """
215
+ # delete everything that isn't part of a camera or a light
216
+ for obj in bpy.data.objects:
217
+ if obj.type not in {"CAMERA", "LIGHT"}:
218
+ bpy.data.objects.remove(obj, do_unlink=True)
219
+
220
+ # delete all the materials
221
+ for material in bpy.data.materials:
222
+ bpy.data.materials.remove(material, do_unlink=True)
223
+
224
+ # delete all the textures
225
+ for texture in bpy.data.textures:
226
+ bpy.data.textures.remove(texture, do_unlink=True)
227
+
228
+ # delete all the images
229
+ for image in bpy.data.images:
230
+ bpy.data.images.remove(image, do_unlink=True)
231
+
232
+
233
+ def load_object(object_path: str) -> None:
234
+ """Loads a model with a supported file extension into the scene.
235
+
236
+ Args:
237
+ object_path (str): Path to the model file.
238
+
239
+ Raises:
240
+ ValueError: If the file extension is not supported.
241
+
242
+ Returns:
243
+ None
244
+ """
245
+ # file_extension = object_path.split(".")[-1].lower()
246
+
247
+ # # load from existing import functions
248
+ # import_function = IMPORT_FUNCTIONS[file_extension]
249
+ # import_function(filepath=object_path)
250
+ bpy.ops.import_scene.obj(filepath=object_path)
251
+ return bpy.context.selected_objects[0]
252
+
253
+
254
+ def scene_bbox(
255
+ single_obj: Optional[bpy.types.Object] = None, ignore_matrix: bool = False
256
+ ) -> Tuple[Vector, Vector]:
257
+ """Returns the bounding box of the scene.
258
+
259
+ Taken from Shap-E rendering script
260
+ (https://github.com/openai/shap-e/blob/main/shap_e/rendering/blender/blender_script.py#L68-L82)
261
+
262
+ Args:
263
+ single_obj (Optional[bpy.types.Object], optional): If not None, only computes
264
+ the bounding box for the given object. Defaults to None.
265
+ ignore_matrix (bool, optional): Whether to ignore the object's matrix. Defaults
266
+ to False.
267
+
268
+ Raises:
269
+ RuntimeError: If there are no objects in the scene.
270
+
271
+ Returns:
272
+ Tuple[Vector, Vector]: The minimum and maximum coordinates of the bounding box.
273
+ """
274
+ bbox_min = (math.inf,) * 3
275
+ bbox_max = (-math.inf,) * 3
276
+ found = False
277
+ for obj in get_scene_meshes() if single_obj is None else [single_obj]:
278
+ found = True
279
+ for coord in obj.bound_box:
280
+ coord = Vector(coord)
281
+ if not ignore_matrix:
282
+ coord = obj.matrix_world @ coord
283
+ bbox_min = tuple(min(x, y) for x, y in zip(bbox_min, coord))
284
+ bbox_max = tuple(max(x, y) for x, y in zip(bbox_max, coord))
285
+
286
+ if not found:
287
+ raise RuntimeError("no objects in scene to compute bounding box for")
288
+
289
+ return Vector(bbox_min), Vector(bbox_max)
290
+
291
+
292
+ def get_scene_root_objects() -> Generator[bpy.types.Object, None, None]:
293
+ """Returns all root objects in the scene.
294
+
295
+ Yields:
296
+ Generator[bpy.types.Object, None, None]: Generator of all root objects in the
297
+ scene.
298
+ """
299
+ for obj in bpy.context.scene.objects.values():
300
+ if not obj.parent:
301
+ yield obj
302
+
303
+
304
+ def get_scene_meshes() -> Generator[bpy.types.Object, None, None]:
305
+ """Returns all meshes in the scene.
306
+
307
+ Yields:
308
+ Generator[bpy.types.Object, None, None]: Generator of all meshes in the scene.
309
+ """
310
+ for obj in bpy.context.scene.objects.values():
311
+ if isinstance(obj.data, (bpy.types.Mesh)):
312
+ yield obj
313
+
314
+
315
+ def get_3x4_RT_matrix_from_blender(cam: bpy.types.Object) -> Matrix:
316
+ """Returns the 3x4 RT matrix from the given camera.
317
+
318
+ Taken from Zero123, which in turn was taken from
319
+ https://github.com/panmari/stanford-shapenet-renderer/blob/master/render_blender.py
320
+
321
+ Args:
322
+ cam (bpy.types.Object): The camera object.
323
+
324
+ Returns:
325
+ Matrix: The 3x4 RT matrix from the given camera.
326
+ """
327
+ # Use matrix_world instead to account for all constraints
328
+ location, rotation = cam.matrix_world.decompose()[0:2]
329
+ R_world2bcam = rotation.to_matrix().transposed()
330
+
331
+ # Use location from matrix_world to account for constraints:
332
+ T_world2bcam = -1 * R_world2bcam @ location
333
+
334
+ # put into 3x4 matrix
335
+ RT = Matrix(
336
+ (
337
+ R_world2bcam[0][:] + (T_world2bcam[0],),
338
+ R_world2bcam[1][:] + (T_world2bcam[1],),
339
+ R_world2bcam[2][:] + (T_world2bcam[2],),
340
+ )
341
+ )
342
+ return RT
343
+
344
+
345
+ def delete_invisible_objects() -> None:
346
+ """Deletes all invisible objects in the scene.
347
+
348
+ Returns:
349
+ None
350
+ """
351
+ bpy.ops.object.select_all(action="DESELECT")
352
+ for obj in scene.objects:
353
+ if obj.hide_viewport or obj.hide_render:
354
+ obj.hide_viewport = False
355
+ obj.hide_render = False
356
+ obj.hide_select = False
357
+ obj.select_set(True)
358
+ bpy.ops.object.delete()
359
+
360
+ # Delete invisible collections
361
+ invisible_collections = [col for col in bpy.data.collections if col.hide_viewport]
362
+ for col in invisible_collections:
363
+ bpy.data.collections.remove(col)
364
+
365
+
366
+ def normalize_scene() -> None:
367
+ """Normalizes the scene by scaling and translating it to fit in a unit cube centered
368
+ at the origin.
369
+
370
+ Mostly taken from the Point-E / Shap-E rendering script
371
+ (https://github.com/openai/point-e/blob/main/point_e/evals/scripts/blender_script.py#L97-L112),
372
+ but fix for multiple root objects: (see bug report here:
373
+ https://github.com/openai/shap-e/pull/60).
374
+
375
+ Returns:
376
+ None
377
+ """
378
+ if len(list(get_scene_root_objects())) > 1:
379
+ # create an empty object to be used as a parent for all root objects
380
+ parent_empty = bpy.data.objects.new("ParentEmpty", None)
381
+ bpy.context.scene.collection.objects.link(parent_empty)
382
+
383
+ # parent all root objects to the empty object
384
+ for obj in get_scene_root_objects():
385
+ if obj != parent_empty:
386
+ obj.parent = parent_empty
387
+
388
+ bbox_min, bbox_max = scene_bbox()
389
+ scale = 1 / max(bbox_max - bbox_min)
390
+ for obj in get_scene_root_objects():
391
+ obj.scale = obj.scale * scale
392
+
393
+ # Apply scale to matrix_world.
394
+ bpy.context.view_layer.update()
395
+ bbox_min, bbox_max = scene_bbox()
396
+ offset = -(bbox_min + bbox_max) / 2
397
+ for obj in get_scene_root_objects():
398
+ obj.matrix_world.translation += offset
399
+ bpy.ops.object.select_all(action="DESELECT")
400
+
401
+ # unparent the camera
402
+ bpy.data.objects["Camera"].parent = None
403
+
404
+
405
+ def delete_missing_textures() -> Dict[str, Any]:
406
+ """Deletes all missing textures in the scene.
407
+
408
+ Returns:
409
+ Dict[str, Any]: Dictionary with keys "count", "files", and "file_path_to_color".
410
+ "count" is the number of missing textures, "files" is a list of the missing
411
+ texture file paths, and "file_path_to_color" is a dictionary mapping the
412
+ missing texture file paths to a random color.
413
+ """
414
+ missing_file_count = 0
415
+ out_files = []
416
+ file_path_to_color = {}
417
+
418
+ # Check all materials in the scene
419
+ for material in bpy.data.materials:
420
+ if material.use_nodes:
421
+ for node in material.node_tree.nodes:
422
+ if node.type == "TEX_IMAGE":
423
+ image = node.image
424
+ if image is not None:
425
+ file_path = bpy.path.abspath(image.filepath)
426
+ if file_path == "":
427
+ # means it's embedded
428
+ continue
429
+
430
+ if not os.path.exists(file_path):
431
+ # Find the connected Principled BSDF node
432
+ connected_node = node.outputs[0].links[0].to_node
433
+
434
+ if connected_node.type == "BSDF_PRINCIPLED":
435
+ if file_path not in file_path_to_color:
436
+ # Set a random color for the unique missing file path
437
+ random_color = [random.random() for _ in range(3)]
438
+ file_path_to_color[file_path] = random_color + [1]
439
+
440
+ connected_node.inputs[
441
+ "Base Color"
442
+ ].default_value = file_path_to_color[file_path]
443
+
444
+ # Delete the TEX_IMAGE node
445
+ material.node_tree.nodes.remove(node)
446
+ missing_file_count += 1
447
+ out_files.append(image.filepath)
448
+ return {
449
+ "count": missing_file_count,
450
+ "files": out_files,
451
+ "file_path_to_color": file_path_to_color,
452
+ }
453
+
454
+
455
+ def _get_random_color() -> Tuple[float, float, float, float]:
456
+ """Generates a random RGB-A color.
457
+
458
+ The alpha value is always 1.
459
+
460
+ Returns:
461
+ Tuple[float, float, float, float]: A random RGB-A color. Each value is in the
462
+ range [0, 1].
463
+ """
464
+ return (random.random(), random.random(), random.random(), 1)
465
+
466
+
467
+ def _apply_color_to_object(
468
+ obj: bpy.types.Object, color: Tuple[float, float, float, float]
469
+ ) -> None:
470
+ """Applies the given color to the object.
471
+
472
+ Args:
473
+ obj (bpy.types.Object): The object to apply the color to.
474
+ color (Tuple[float, float, float, float]): The color to apply to the object.
475
+
476
+ Returns:
477
+ None
478
+ """
479
+ mat = bpy.data.materials.new(name=f"RandomMaterial_{obj.name}")
480
+ mat.use_nodes = True
481
+ nodes = mat.node_tree.nodes
482
+ principled_bsdf = nodes.get("Principled BSDF")
483
+ if principled_bsdf:
484
+ principled_bsdf.inputs["Base Color"].default_value = color
485
+ obj.data.materials.append(mat)
486
+
487
+
488
+ def apply_single_random_color_to_all_objects() -> Tuple[float, float, float, float]:
489
+ """Applies a single random color to all objects in the scene.
490
+
491
+ Returns:
492
+ Tuple[float, float, float, float]: The random color that was applied to all
493
+ objects.
494
+ """
495
+ rand_color = _get_random_color()
496
+ for obj in bpy.context.scene.objects:
497
+ if obj.type == "MESH":
498
+ _apply_color_to_object(obj, rand_color)
499
+ return rand_color
500
+
501
+
502
+ class MetadataExtractor:
503
+ """Class to extract metadata from a Blender scene."""
504
+
505
+ def __init__(
506
+ self, object_path: str, scene: bpy.types.Scene, bdata: bpy.types.BlendData
507
+ ) -> None:
508
+ """Initializes the MetadataExtractor.
509
+
510
+ Args:
511
+ object_path (str): Path to the object file.
512
+ scene (bpy.types.Scene): The current scene object from `bpy.context.scene`.
513
+ bdata (bpy.types.BlendData): The current blender data from `bpy.data`.
514
+
515
+ Returns:
516
+ None
517
+ """
518
+ self.object_path = object_path
519
+ self.scene = scene
520
+ self.bdata = bdata
521
+
522
+ def get_poly_count(self) -> int:
523
+ """Returns the total number of polygons in the scene."""
524
+ total_poly_count = 0
525
+ for obj in self.scene.objects:
526
+ if obj.type == "MESH":
527
+ total_poly_count += len(obj.data.polygons)
528
+ return total_poly_count
529
+
530
+ def get_vertex_count(self) -> int:
531
+ """Returns the total number of vertices in the scene."""
532
+ total_vertex_count = 0
533
+ for obj in self.scene.objects:
534
+ if obj.type == "MESH":
535
+ total_vertex_count += len(obj.data.vertices)
536
+ return total_vertex_count
537
+
538
+ def get_edge_count(self) -> int:
539
+ """Returns the total number of edges in the scene."""
540
+ total_edge_count = 0
541
+ for obj in self.scene.objects:
542
+ if obj.type == "MESH":
543
+ total_edge_count += len(obj.data.edges)
544
+ return total_edge_count
545
+
546
+ def get_lamp_count(self) -> int:
547
+ """Returns the number of lamps in the scene."""
548
+ return sum(1 for obj in self.scene.objects if obj.type == "LIGHT")
549
+
550
+ def get_mesh_count(self) -> int:
551
+ """Returns the number of meshes in the scene."""
552
+ return sum(1 for obj in self.scene.objects if obj.type == "MESH")
553
+
554
+ def get_material_count(self) -> int:
555
+ """Returns the number of materials in the scene."""
556
+ return len(self.bdata.materials)
557
+
558
+ def get_object_count(self) -> int:
559
+ """Returns the number of objects in the scene."""
560
+ return len(self.bdata.objects)
561
+
562
+ def get_animation_count(self) -> int:
563
+ """Returns the number of animations in the scene."""
564
+ return len(self.bdata.actions)
565
+
566
+ def get_linked_files(self) -> List[str]:
567
+ """Returns the filepaths of all linked files."""
568
+ image_filepaths = self._get_image_filepaths()
569
+ material_filepaths = self._get_material_filepaths()
570
+ linked_libraries_filepaths = self._get_linked_libraries_filepaths()
571
+
572
+ all_filepaths = (
573
+ image_filepaths | material_filepaths | linked_libraries_filepaths
574
+ )
575
+ if "" in all_filepaths:
576
+ all_filepaths.remove("")
577
+ return list(all_filepaths)
578
+
579
+ def _get_image_filepaths(self) -> Set[str]:
580
+ """Returns the filepaths of all images used in the scene."""
581
+ filepaths = set()
582
+ for image in self.bdata.images:
583
+ if image.source == "FILE":
584
+ filepaths.add(bpy.path.abspath(image.filepath))
585
+ return filepaths
586
+
587
+ def _get_material_filepaths(self) -> Set[str]:
588
+ """Returns the filepaths of all images used in materials."""
589
+ filepaths = set()
590
+ for material in self.bdata.materials:
591
+ if material.use_nodes:
592
+ for node in material.node_tree.nodes:
593
+ if node.type == "TEX_IMAGE":
594
+ image = node.image
595
+ if image is not None:
596
+ filepaths.add(bpy.path.abspath(image.filepath))
597
+ return filepaths
598
+
599
+ def _get_linked_libraries_filepaths(self) -> Set[str]:
600
+ """Returns the filepaths of all linked libraries."""
601
+ filepaths = set()
602
+ for library in self.bdata.libraries:
603
+ filepaths.add(bpy.path.abspath(library.filepath))
604
+ return filepaths
605
+
606
+ def get_scene_size(self) -> Dict[str, list]:
607
+ """Returns the size of the scene bounds in meters."""
608
+ bbox_min, bbox_max = scene_bbox()
609
+ return {"bbox_max": list(bbox_max), "bbox_min": list(bbox_min)}
610
+
611
+ def get_shape_key_count(self) -> int:
612
+ """Returns the number of shape keys in the scene."""
613
+ total_shape_key_count = 0
614
+ for obj in self.scene.objects:
615
+ if obj.type == "MESH":
616
+ shape_keys = obj.data.shape_keys
617
+ if shape_keys is not None:
618
+ total_shape_key_count += (
619
+ len(shape_keys.key_blocks) - 1
620
+ ) # Subtract 1 to exclude the Basis shape key
621
+ return total_shape_key_count
622
+
623
+ def get_armature_count(self) -> int:
624
+ """Returns the number of armatures in the scene."""
625
+ total_armature_count = 0
626
+ for obj in self.scene.objects:
627
+ if obj.type == "ARMATURE":
628
+ total_armature_count += 1
629
+ return total_armature_count
630
+
631
+ def read_file_size(self) -> int:
632
+ """Returns the size of the file in bytes."""
633
+ return os.path.getsize(self.object_path)
634
+
635
+ def get_metadata(self) -> Dict[str, Any]:
636
+ """Returns the metadata of the scene.
637
+
638
+ Returns:
639
+ Dict[str, Any]: Dictionary of the metadata with keys for "file_size",
640
+ "poly_count", "vert_count", "edge_count", "material_count", "object_count",
641
+ "lamp_count", "mesh_count", "animation_count", "linked_files", "scene_size",
642
+ "shape_key_count", and "armature_count".
643
+ """
644
+ return {
645
+ "file_size": self.read_file_size(),
646
+ "poly_count": self.get_poly_count(),
647
+ "vert_count": self.get_vertex_count(),
648
+ "edge_count": self.get_edge_count(),
649
+ "material_count": self.get_material_count(),
650
+ "object_count": self.get_object_count(),
651
+ "lamp_count": self.get_lamp_count(),
652
+ "mesh_count": self.get_mesh_count(),
653
+ "animation_count": self.get_animation_count(),
654
+ "linked_files": self.get_linked_files(),
655
+ "scene_size": self.get_scene_size(),
656
+ "shape_key_count": self.get_shape_key_count(),
657
+ "armature_count": self.get_armature_count(),
658
+ }
659
+
660
+
661
+ def set_background_color(r, g, b):
662
+ # Get the current scene
663
+ scene = bpy.context.scene
664
+
665
+ # Create a new world background if none exists
666
+ if not scene.world:
667
+ scene.world = bpy.data.worlds.new("World")
668
+
669
+ # Set the background color
670
+ scene.world.use_nodes = True
671
+ bg_node = scene.world.node_tree.nodes['Background']
672
+ bg_node.inputs['Color'].default_value = (r, g, b, 1) # set the background to the given RGB value
673
+
674
+ # Disable transparency
675
+ scene.render.film_transparent = False
676
+
677
+
678
+ def render_object(
679
+ object_file: str,
680
+ num_renders: int,
681
+ only_northern_hemisphere: bool,
682
+ output_dir: str,
683
+ ) -> None:
684
+ """Saves rendered images with its camera matrix and metadata of the object.
685
+
686
+ Args:
687
+ object_file (str): Path to the object file.
688
+ num_renders (int): Number of renders to save of the object.
689
+ only_northern_hemisphere (bool): Whether to only render sides of the object that
690
+ are in the northern hemisphere. This is useful for rendering objects that
691
+ are photogrammetrically scanned, as the bottom of the object often has
692
+ holes.
693
+ output_dir (str): Path to the directory where the rendered images and metadata
694
+ will be saved.
695
+
696
+ Returns:
697
+ None
698
+ """
699
+ os.makedirs(output_dir, exist_ok=True)
700
+
701
+ # load the object
702
+ reset_scene()
703
+ obj = load_object(object_file)
704
+
705
+ # Set up cameras
706
+ cam = scene.objects["Camera"]
707
+ cam.data.lens = 35
708
+ cam.data.sensor_width = 32
709
+
710
+ # Set up camera constraints
711
+ cam_constraint = cam.constraints.new(type="TRACK_TO")
712
+ cam_constraint.track_axis = "TRACK_NEGATIVE_Z"
713
+ cam_constraint.up_axis = "UP_Y"
714
+ # empty = bpy.data.objects.new("Empty", None)
715
+ # scene.collection.objects.link(empty)
716
+ # cam_constraint.target = empty
717
+
718
+ # Extract the metadata. This must be done before normalizing the scene to get
719
+ # accurate bounding box information.
720
+ metadata_extractor = MetadataExtractor(
721
+ object_path=object_file, scene=scene, bdata=bpy.data
722
+ )
723
+ metadata = metadata_extractor.get_metadata()
724
+
725
+ # delete all objects that are not meshes
726
+ # if object_file.lower().endswith(".usdz"):
727
+ # # don't delete missing textures on usdz files, lots of them are embedded
728
+ # missing_textures = None
729
+ # else:
730
+ missing_textures = delete_missing_textures()
731
+ metadata["missing_textures"] = missing_textures
732
+
733
+ # possibly apply a random color to all objects
734
+ # if object_file.endswith(".stl") or object_file.endswith(".ply"):
735
+ # assert len(bpy.context.selected_objects) == 1
736
+ # rand_color = apply_single_random_color_to_all_objects()
737
+ # metadata["random_color"] = rand_color
738
+ # else:
739
+ metadata["random_color"] = None
740
+
741
+ # save metadata
742
+ metadata_path = os.path.join(output_dir, "metadata.json")
743
+ os.makedirs(os.path.dirname(metadata_path), exist_ok=True)
744
+ with open(metadata_path, "w", encoding="utf-8") as f:
745
+ json.dump(metadata, f, sort_keys=True, indent=2)
746
+
747
+ # normalize the scene
748
+ normalize_scene()
749
+
750
+ # set background color
751
+ set_background_color(0.5, 0.5, 0.5) # gray (RGB: 0.5, 0.5, 0.5)
752
+
753
+ # randomize the lighting
754
+ randomize_lighting()
755
+
756
+ # render the images
757
+ for i in range(num_renders):
758
+
759
+ theta = i * np.pi / 36 # rotate 5 degrees (pi/36 radians) for each render
760
+ # obj.rotation_euler.x = theta # rotate around X axis
761
+ obj.rotation_euler.y = theta # rotate around Y axis
762
+ # obj.rotation_euler.z = theta # rotate around Z axis
763
+
764
+ # set camera
765
+ camera = set_camera()
766
+
767
+ # render the image
768
+ render_path = os.path.join(output_dir, f"{i:03d}.png")
769
+ scene.render.filepath = render_path
770
+ bpy.ops.render.render(write_still=True)
771
+
772
+ # # save camera RT matrix
773
+ # rt_matrix = get_3x4_RT_matrix_from_blender(camera)
774
+ # rt_matrix_path = os.path.join(output_dir, f"{i:03d}.npy")
775
+ # np.save(rt_matrix_path, rt_matrix)
776
+
777
+ def render_object_mask(
778
+ object_file: str,
779
+ num_renders: int,
780
+ output_dir: str,
781
+ ) -> None:
782
+ """Saves rendered masks of the object directly as npy files."""
783
+
784
+ os.makedirs(output_dir, exist_ok=True)
785
+
786
+ # Load the object
787
+ reset_scene()
788
+ obj = load_object(object_file)
789
+
790
+ # Set up cameras
791
+ cam = scene.objects["Camera"]
792
+ cam.data.lens = 35
793
+ cam.data.sensor_width = 32
794
+
795
+ # Set up camera constraints
796
+ cam_constraint = cam.constraints.new(type="TRACK_TO")
797
+ cam_constraint.track_axis = "TRACK_NEGATIVE_Z"
798
+ cam_constraint.up_axis = "UP_Y"
799
+
800
+ # normalize the scene
801
+ normalize_scene()
802
+
803
+ # Assign a simple (white) material to the object
804
+ mat = bpy.data.materials.new(name="WhiteMaterial")
805
+ mat.use_nodes = True
806
+ nodes = mat.node_tree.nodes
807
+ principled_bsdf = nodes.get("Principled BSDF")
808
+ if principled_bsdf:
809
+ principled_bsdf.inputs["Base Color"].default_value = (1, 1, 1, 1)
810
+ principled_bsdf.inputs["Emission"].default_value = (1, 1, 1, 1)
811
+ principled_bsdf.inputs["Emission Strength"].default_value = 2.0
812
+
813
+ # Apply the white material to the object
814
+ if obj.data.materials:
815
+ obj.data.materials.clear()
816
+ obj.data.materials.append(mat)
817
+
818
+ # Set the background to black (same approach as in render_object)
819
+ set_background_color(0, 0, 0)
820
+
821
+ # Reuse the render_object lighting setup
822
+ randomize_lighting()
823
+
824
+ # render the masks (exact copy of the render_object render loop structure)
825
+ for i in range(num_renders):
826
+ print(f"Rendering mask {i+1}/{num_renders}")
827
+
828
+ theta = i * np.pi / 36
829
+ obj.rotation_euler.y = theta
830
+
831
+ # set camera (identical to render_object)
832
+ camera = set_camera()
833
+
834
+ # Save temporarily as PNG, then read it back and delete it
835
+ temp_png_path = os.path.join(output_dir, f"temp_{i:03d}.png")
836
+ scene.render.filepath = temp_png_path
837
+ bpy.ops.render.render(write_still=True)
838
+
839
+ # Use Blender's built-in method to read the PNG and convert it to a mask
840
+ try:
841
+ # Load the image with Blender
842
+ img = bpy.data.images.load(temp_png_path)
843
+
844
+ # Get the image size
845
+ width, height = img.size
846
+
847
+ # Get the pixel data
848
+ pixel_data = np.array(img.pixels[:]).reshape((height, width, 4)) # RGBA
849
+
850
+ # Convert to grayscale and binarize
851
+ gray = np.mean(pixel_data[:, :, :3], axis=2) # use only the RGB channels
852
+ mask = (gray > 0.5).astype(np.uint8) # binarize
853
+
854
+ # Flip the Y axis (Blender's image coordinate system is upside down)
855
+ mask = np.flipud(mask)
856
+
857
+ # Save the mask as npy
858
+ npy_path = os.path.join(output_dir, f"{i:03d}_mask.npy")
859
+ np.save(npy_path, mask)
860
+ print(f"Saved mask to {npy_path}, mask shape: {mask.shape}")
861
+
862
+ # Cleanup: remove the Blender image data and the temporary file
863
+ bpy.data.images.remove(img)
864
+ os.remove(temp_png_path)
865
+
866
+ except Exception as e:
867
+ print(f"Failed to process mask for frame {i}: {e}")
868
+ # On error, still delete the temporary file
869
+ if os.path.exists(temp_png_path):
870
+ os.remove(temp_png_path)
871
+
872
+ def get_directories(input_path, output_path):
873
+ input_dir = []
874
+ output_dir = []
875
+ for root, dirs, files in os.walk(input_path):
876
+ if not dirs: # if there are no subdirectories, treat it as the lowest-level subdirectory
877
+ input_dir.append(root + "/Scan.obj")
878
+ no_head = root.replace(input_path, '')
879
+ output_dir.append(output_path + no_head)
880
+ return input_dir, output_dir
881
+
882
+ if __name__ == "__main__":
883
+ parser = argparse.ArgumentParser()
884
+ parser.add_argument(
885
+ "--object_path",
886
+ type=str,
887
+ required=True,
888
+ help="Path to the object file",
889
+ )
890
+ parser.add_argument(
891
+ "--output_dir",
892
+ type=str,
893
+ required=True,
894
+ help="Path to the directory where the rendered images and metadata will be saved.",
895
+ )
896
+ parser.add_argument(
897
+ "--engine",
898
+ type=str,
899
+ default="BLENDER_EEVEE",
900
+ choices=["CYCLES", "BLENDER_EEVEE"],
901
+ )
902
+ parser.add_argument(
903
+ "--only_northern_hemisphere",
904
+ action="store_true",
905
+ help="Only render the northern hemisphere of the object.",
906
+ default=False,
907
+ )
908
+ parser.add_argument(
909
+ "--num_renders",
910
+ type=int,
911
+ default=72,
912
+ help="Number of renders to save of the object.",
913
+ )
914
+ parser.add_argument(
915
+ "--save_image",
916
+ type=str,
917
+ choices=["True", "False"],
918
+ default="True",
919
+ help="Whether to save the rendered images.",
920
+ )
921
+
922
+
923
+ parser.add_argument(
924
+ "--save_mask",
925
+ type=str,
926
+ choices=["True", "False"],
927
+ default="False",
928
+ help="Whether to save the rendered masks as npy files.",
929
+ )
930
+ argv = sys.argv[sys.argv.index("--") + 1 :]
931
+ args = parser.parse_args(argv)
932
+ args.save_image = args.save_image == "True"
933
+ args.save_mask = args.save_mask == "True"
934
+
935
+ context = bpy.context
936
+ scene = context.scene
937
+ render = scene.render
938
+
939
+ # Set render settings
940
+ render.engine = args.engine
941
+ render.image_settings.file_format = "PNG"
942
+ render.image_settings.color_mode = "RGB"
943
+ render.resolution_x = 128
944
+ render.resolution_y = 128
945
+ render.resolution_percentage = 100
946
+
947
+ # Set cycles settings
948
+ scene.cycles.device = "GPU"
949
+ scene.cycles.samples = 128
950
+ scene.cycles.diffuse_bounces = 1
951
+ scene.cycles.glossy_bounces = 1
952
+ scene.cycles.transparent_max_bounces = 3
953
+ scene.cycles.transmission_bounces = 3
954
+ scene.cycles.filter_width = 0.01
955
+ scene.cycles.use_denoising = True
956
+ scene.render.film_transparent = True
957
+ bpy.context.preferences.addons["cycles"].preferences.get_devices()
958
+ bpy.context.preferences.addons[
959
+ "cycles"
960
+ ].preferences.compute_device_type = "CUDA" # or "OPENCL"
961
+
962
+ # Get all input directories and output directories
963
+ input_dir, output_dir = get_directories(args.object_path, args.output_dir)
964
+ num_render_files = len(input_dir)
965
+ for i in range(num_render_files):
966
+ # Skip per task (not per directory), so a later --save_mask pass can still
967
+ # add masks to object directories that already contain rendered images.
968
+ if args.save_image and not os.path.exists(
969
+ os.path.join(output_dir[i], f"{args.num_renders - 1:03d}.png")
970
+ ):
971
+ # Load the object and render the images
972
+ render_object(
973
+ object_file=input_dir[i],
974
+ num_renders=args.num_renders,
975
+ only_northern_hemisphere=args.only_northern_hemisphere,
976
+ output_dir=output_dir[i],
977
+ )
978
+
979
+ if args.save_mask and not os.path.exists(
980
+ os.path.join(output_dir[i], f"{args.num_renders - 1:03d}_mask.npy")
981
+ ):
982
+ # Render masks
983
+ render_object_mask(
984
+ object_file=input_dir[i],
985
+ num_renders=args.num_renders,
986
+ output_dir=output_dir[i],
987
+ )