yoda-chicken commited on
Commit
496f04e
·
verified ·
1 Parent(s): 35659bc

Upload generate_pseudokitchens.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. generate_pseudokitchens.py +739 -0
generate_pseudokitchens.py ADDED
@@ -0,0 +1,739 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Module for creating PseudoKitchens datasets using Blender."""
2
+ import bpy
3
+ import mathutils
4
+ import random
5
+ import math
6
+ import json
7
+ from math import radians, degrees
8
+ from mathutils import Vector, Euler
9
+ import os
10
+ from tqdm import trange
11
+ import argparse
12
+ from pathlib import Path
13
+
14
+ def parse_args():
15
+ """Parse command line arguments."""
16
+ parser = argparse.ArgumentParser(description="Create PseudoKitchens datasets")
17
+
18
+ subparsers = parser.add_subparsers(dest="command", required=True)
19
+
20
+ create_parser = subparsers.add_parser("create", help="Create a Pseudokitchens dataset")
21
+ create_parser.add_argument("--train-size", type=int, required=True, help="Number of samples for training")
22
+ create_parser.add_argument("--val-size", type=int, required=True, help="Number of samples for validation")
23
+ create_parser.add_argument("--test-size", type=int, required=True, help="Number of samples for testing")
24
+ create_parser.add_argument("--dataset-dir", type=Path, required=True, help="Path to the dataset output directory")
25
+
26
+ generate_examples_parser = subparsers.add_parser("generate_examples", help="Generate instances for a PseudoKitchens dataset")
27
+ generate_examples_parser.add_argument("--dir", type=Path, required=True, help="Directory to save generated instances")
28
+ generate_examples_parser.add_argument("--first-number", type=int, required=True, help="First number to use for naming instances")
29
+ generate_examples_parser.add_argument("--last-number", type=int, required=True, help="Last number to use for naming instances")
30
+ generate_examples_parser.add_argument("--filename-length", type=int, default=0, help="Length of the filename for each instance")
31
+
32
+ ingredient_distribution_parser = subparsers.add_parser("ingredient_distribution", help="Print the distribution of ingredients in the instances in a folder")
33
+ ingredient_distribution_parser.add_argument("--dir", type=Path, required=True, help="Directory containing the instances to analyse")
34
+
35
+ args = parser.parse_args()
36
+
37
+ return args
38
+
39
+ def hide(obj):
40
+ """Hide an object and all its children in Blender."""
41
+ obj.hide_render = True
42
+ obj.hide_set(True)
43
+ for child in obj.children:
44
+ hide(child)
45
+
46
+ def show(obj):
47
+ """Show an object and all its children in Blender."""
48
+ obj.hide_render = False
49
+ obj.hide_set(False)
50
+ for child in obj.children:
51
+ show(child)
52
+
53
+ kelvin_table = {
54
+ 3000: (255, 180, 107),
55
+ 3100: (255, 184, 114),
56
+ 3200: (255, 187, 120),
57
+ 3300: (255, 190, 126),
58
+ 3400: (255, 193, 132),
59
+ 3500: (255, 196, 137),
60
+ 3600: (255, 199, 143),
61
+ 3700: (255, 201, 148),
62
+ 3800: (255, 204, 153),
63
+ 3900: (255, 206, 159),
64
+ 4000: (255, 209, 163),
65
+ 4100: (255, 211, 168),
66
+ 4200: (255, 213, 173),
67
+ 4300: (255, 215, 177),
68
+ 4400: (255, 217, 182),
69
+ 4500: (255, 219, 186),
70
+ 4600: (255, 221, 190),
71
+ 4700: (255, 223, 194),
72
+ 4800: (255, 225, 198),
73
+ 4900: (255, 227, 202),
74
+ 5000: (255, 228, 206),
75
+ 5100: (255, 230, 210),
76
+ 5200: (255, 232, 213),
77
+ 5300: (255, 233, 217),
78
+ 5400: (255, 235, 220),
79
+ 5500: (255, 236, 224),
80
+ 5600: (255, 238, 227),
81
+ 5700: (255, 239, 230),
82
+ 5800: (255, 240, 233),
83
+ 5900: (255, 242, 236),
84
+ 6000: (255, 243, 239),
85
+ 6100: (255, 244, 242),
86
+ 6200: (255, 245, 245),
87
+ 6300: (255, 246, 247),
88
+ 6400: (255, 248, 251),
89
+ 6500: (255, 249, 253),
90
+ 6600: (254, 249, 255),
91
+ 6700: (252, 247, 255),
92
+ 6800: (249, 246, 255),
93
+ 6900: (247, 245, 255),
94
+ 7000: (245, 243, 255),
95
+ 7100: (243, 242, 255),
96
+ 7200: (240, 241, 255),
97
+ 7300: (239, 240, 255),
98
+ 7400: (237, 239, 255),
99
+ 7500: (235, 238, 255),
100
+ 7600: (233, 237, 255),
101
+ 7700: (231, 236, 255),
102
+ 7800: (230, 235, 255),
103
+ 7900: (228, 234, 255),
104
+ 8000: (227, 233, 255),
105
+ }
106
+
107
+ ingredient_groups = {
108
+ "Fruit": ["Banana", "Orange", "Apple", "Pear", "Pineapple"],
109
+ "Vegetables": ["Onion", "Carrot", "Potato", "Pepper", "Courgette"],
110
+ "Pasta": ["Macaroni", "Spaghetti"]
111
+ }
112
+
113
+ recipes = {
114
+ "Fruit Salad": [
115
+ "Fruit"
116
+ ],
117
+ "Vegetable Pasta": [
118
+ "Pasta",
119
+ "Onion",
120
+ "Garlic",
121
+ "Oil",
122
+ "Vegetables",
123
+ "Spice",
124
+ "Tin Tomatoes"
125
+ ],
126
+ "Risotto": [
127
+ "Cheese",
128
+ "Onion",
129
+ "Garlic",
130
+ "Vegetables",
131
+ "Oil",
132
+ "Spice",
133
+ "Rice"
134
+ ],
135
+ "Chips": [
136
+ "Potato",
137
+ "Oil",
138
+ "Flour",
139
+ "Garlic",
140
+ "Spice"
141
+ ],
142
+ "Chilli": [
143
+ "Mince",
144
+ "Oil",
145
+ "Onion",
146
+ "Garlic",
147
+ "Chilli",
148
+ "Tin Tomatoes",
149
+ "Spice",
150
+ "Rice"
151
+ ],
152
+ "Smoothie": [
153
+ "Milk",
154
+ "Yoghurt",
155
+ "Fruit"
156
+ ],
157
+ "Hot Chocolate": [
158
+ "Chocolate",
159
+ "Milk"
160
+ ],
161
+ "Banana Bread": [
162
+ "Butter",
163
+ "Sugar",
164
+ "Egg",
165
+ "Flour",
166
+ "Banana"
167
+ ],
168
+ "Chocolate Fudge Cake": [
169
+ "Egg",
170
+ "Sugar",
171
+ "Oil",
172
+ "Flour",
173
+ "Chocolate",
174
+ "Syrup",
175
+ "Milk"
176
+ ],
177
+ "Carbonara": [
178
+ "Garlic",
179
+ "Meat",
180
+ "Butter",
181
+ "Cheese",
182
+ "Egg",
183
+ "Spaghetti",
184
+ "Spice"
185
+ ]
186
+ }
187
+ recipes_ordered = sorted(recipes.keys())
188
+
189
+ ingredients = set()
190
+ for group_ingredients in ingredient_groups.values():
191
+ ingredients.update(group_ingredients)
192
+
193
+ for recipe_ingredients in recipes.values():
194
+ for ingredient in recipe_ingredients:
195
+ if ingredient not in ingredient_groups:
196
+ ingredients.add(ingredient)
197
+
198
+ def count_objects():
199
+ """Count all objects, random objects, and kitchens in the Blender scene."""
200
+ ingredient_counts = {}
201
+ for ingredient in sorted(ingredients):
202
+ i = 1
203
+ while f"{ingredient} {i}" in bpy.data.objects:
204
+ i += 1
205
+
206
+ assert i > 1, f"Could not find any {ingredient} objects."
207
+
208
+ ingredient_counts[ingredient] = i - 1
209
+
210
+ print(f"Found {i - 1} {ingredient} object(s).")
211
+
212
+ n_random_objects = 0
213
+ while f"Object {n_random_objects + 1}" in bpy.data.objects:
214
+ n_random_objects += 1
215
+ print(f"Found {n_random_objects} random object(s).")
216
+
217
+ n_kitchens = 0
218
+ while f"Kitchen {n_kitchens + 1}" in bpy.data.collections:
219
+ kitchen_name = f"Kitchen {n_kitchens + 1}"
220
+ n_kitchens += 1
221
+ print(f"Found {n_kitchens} kitchen(s).")
222
+
223
+ return {
224
+ "ingredient_counts": ingredient_counts,
225
+ "n_random_objects": n_random_objects,
226
+ "n_kitchens": n_kitchens
227
+ }
228
+
229
+ def hide_all(object_counts):
230
+ """Hide all objects and collections based on the provided counts."""
231
+ vlayer = bpy.context.scene.view_layers["ViewLayer"]
232
+ for ingredient, count in object_counts["ingredient_counts"].items():
233
+ for i in range(1, count + 1):
234
+ hide(bpy.data.objects[f"{ingredient} {i}"])
235
+ for i in range(1, object_counts["n_random_objects"] + 1):
236
+ hide(bpy.data.objects[f"Object {i}"])
237
+ for i in range(1, object_counts["n_kitchens"] + 1):
238
+ bpy.data.collections[f"Kitchen {i}"].hide_render = True
239
+ vlayer.layer_collection.children["Kitchens"].children[f"Kitchen {i}"].hide_viewport = True
240
+
241
+ def set_random_floor():
242
+ """Set a random floor material."""
243
+ floor_number = random.choice([1, 2, 3, 4, 5])
244
+ bpy.data.objects["Walls"].data.materials[1] = bpy.data.materials[f"Floor {floor_number}"]
245
+ return floor_number
246
+
247
+ def set_random_wall():
248
+ """Set a random wall material."""
249
+ wall_number = random.choice([1, 2, 3, 4, 5])
250
+ bpy.data.objects["Walls"].data.materials[0] = bpy.data.materials[f"Wall {wall_number}"]
251
+ return wall_number
252
+
253
+ def set_random_light_position():
254
+ """Set a random position for the light object within its allowed range."""
255
+ light_object = bpy.data.objects["Light"]
256
+
257
+ x_min = light_object["x_min"]
258
+ x_max = light_object["x_max"]
259
+ random_x = random.uniform(x_min, x_max)
260
+
261
+ y_min = light_object["y_min"]
262
+ y_max = light_object["y_max"]
263
+ random_y = random.uniform(y_min, y_max)
264
+
265
+ position = Vector((random_x, random_y, light_object.location.z))
266
+
267
+ light_object.location = position
268
+
269
+ return (random_x, random_y)
270
+
271
+ def set_random_light_power():
272
+ """Set a random power for the light object within its allowed range."""
273
+ light_object = bpy.data.objects["Light"]
274
+
275
+ power_min = light_object["power_min"]
276
+ power_max = light_object["power_max"]
277
+
278
+ random_power = random.uniform(power_min, power_max)
279
+
280
+ light_object.data.energy = random_power
281
+
282
+ return random_power
283
+
284
+ def set_random_light_colour():
285
+ """Set a random colour for the light object based on a Kelvin table."""
286
+ light_object = bpy.data.objects["Light"]
287
+
288
+ temperature = random.choice(list(kelvin_table.keys()))
289
+ c = kelvin_table[temperature]
290
+ colour = (c[0] / 255.0, c[1] / 255.0, c[2] / 255.0)
291
+
292
+ light_object.data.color = colour
293
+ return colour
294
+
295
+ def set_random_camera_position(kitchen_name):
296
+ """Set a random position and rotation for the kitchen camera."""
297
+ camera_pivot_object = bpy.data.objects[f"{kitchen_name} camera pivot"]
298
+
299
+ rotation_x_min = camera_pivot_object["rotation_x_min"]
300
+ rotation_x_max = camera_pivot_object["rotation_x_max"]
301
+ random_rotation_x = random.uniform(rotation_x_min, rotation_x_max)
302
+
303
+ rotation_z_min = camera_pivot_object["rotation_z_min"]
304
+ rotation_z_max = camera_pivot_object["rotation_z_max"]
305
+ random_rotation_z = random.uniform(rotation_z_min, rotation_z_max)
306
+
307
+ scale_min = camera_pivot_object["scale_min"]
308
+ scale_max = camera_pivot_object["scale_max"]
309
+ random_scale = random.uniform(scale_min, scale_max)
310
+
311
+ camera_pivot_object.rotation_euler = (random_rotation_x, 0, random_rotation_z)
312
+
313
+ camera_pivot_object.scale = (random_scale, random_scale, random_scale)
314
+
315
+ return random_rotation_x, random_rotation_z, random_scale
316
+
317
+ def set_random_egg_box_openness():
318
+ """Set a random rotation for the egg box cap."""
319
+ random_rotation_x = radians(random.uniform(-147, 0))
320
+ bpy.data.objects["Egg 5"].pose.bones["CAP"].rotation_euler = (random_rotation_x, 0, 0)
321
+ return random_rotation_x
322
+
323
+ def apply_random_transform(object_name, scale_range=(0.8, 1.2)):
324
+ """Apply random rotation and scaling to object."""
325
+ obj = bpy.data.objects[object_name]
326
+
327
+ # Random rotation around Z-axis (0 to 360 degrees)
328
+ random_rotation = random.uniform(0, 2 * math.pi)
329
+ obj.rotation_euler = (0, 0, random_rotation)
330
+
331
+ # Random uniform scaling
332
+ random_scale = random.uniform(scale_range[0], scale_range[1])
333
+ obj.scale = (random_scale, random_scale, random_scale)
334
+
335
+ # Update the scene to reflect changes
336
+ bpy.context.view_layer.update()
337
+
338
+ return degrees(random_rotation), random_scale
339
+
340
+ class Surfaces:
341
+ """Manages multiple flat surfaces and tracks object placements."""
342
+
343
+ def __init__(self, kitchen_name):
344
+ """
345
+ Initialize surfaces for a given kitchen.
346
+
347
+ Args:
348
+ kitchen_name: String identifier for the kitchen (e.g., "Kitchen 1")
349
+ """
350
+ self.kitchen_name = kitchen_name
351
+ self.surfaces = {}
352
+ self.placed_objects = {} # surface_name -> list of object bounds
353
+
354
+ # Find all surfaces matching the pattern
355
+ self._discover_surfaces()
356
+
357
+ def _discover_surfaces(self):
358
+ """Find all surfaces matching the pattern '{kitchen} surface {i}'."""
359
+ i = 1
360
+ while f"{self.kitchen_name} surface {i}" in bpy.data.objects:
361
+ surface_name = f"{self.kitchen_name} surface {i}"
362
+ surface_obj = bpy.data.objects[surface_name]
363
+ if surface_obj.type == "MESH":
364
+ # Calculate surface area and store surface info
365
+ bounds = self._get_object_bounds(surface_obj)
366
+ area = bounds["size"].x * bounds["size"].y
367
+
368
+ self.surfaces[surface_name] = {
369
+ "object": surface_obj,
370
+ "area": area,
371
+ "bounds": bounds,
372
+ "z_level": bounds["max"].z # Assuming flat surface
373
+ }
374
+ self.placed_objects[surface_name] = []
375
+ print(f"Found surface: {surface_name} (area: {area:.2f})")
376
+ else:
377
+ print(f"Warning: {surface_name} is not a mesh object")
378
+ i += 1
379
+
380
+ if not self.surfaces:
381
+ raise ValueError(f"No surfaces found for kitchen '{self.kitchen_name}'")
382
+
383
+ print(f"Discovered {len(self.surfaces)} surfaces for {self.kitchen_name}")
384
+
385
+ def _get_object_bounds(self, obj):
386
+ """Get the bounding box of an object and all its children in world coordinates."""
387
+
388
+ def collect_bounds(current_obj):
389
+ """Recursively collect bounding box corners from object and its children."""
390
+ # Add current object's bounding box corners
391
+ if current_obj.type == "MESH":
392
+ depsgraph = bpy.context.evaluated_depsgraph_get()
393
+ eval_obj = current_obj.evaluated_get(depsgraph)
394
+ mesh = eval_obj.to_mesh()
395
+ vertices = [current_obj.matrix_world @ v.co for v in mesh.vertices]
396
+
397
+ min_x = min(vertex.x for vertex in vertices)
398
+ max_x = max(vertex.x for vertex in vertices)
399
+ min_y = min(vertex.y for vertex in vertices)
400
+ max_y = max(vertex.y for vertex in vertices)
401
+ min_z = min(vertex.z for vertex in vertices)
402
+ max_z = max(vertex.z for vertex in vertices)
403
+ else:
404
+ min_x = min_y = min_z = float("inf")
405
+ max_x = max_y = max_z = float("-inf")
406
+
407
+ # Recursively process children
408
+ for child in current_obj.children:
409
+ min_x_c, min_y_c, min_z_c, max_x_c, max_y_c, max_z_c = collect_bounds(child)
410
+ min_x = min(min_x, min_x_c)
411
+ min_y = min(min_y, min_y_c)
412
+ min_z = min(min_z, min_z_c)
413
+ max_x = max(max_x, max_x_c)
414
+ max_y = max(max_y, max_y_c)
415
+ max_z = max(max_z, max_z_c)
416
+
417
+ return min_x, min_y, min_z, max_x, max_y, max_z
418
+
419
+ # Collect all bounding box corners
420
+ min_x, min_y, min_z, max_x, max_y, max_z = collect_bounds(obj)
421
+
422
+ min_bound = Vector((min_x, min_y, min_z))
423
+ max_bound = Vector((max_x, max_y, max_z))
424
+
425
+ # Calculate displacement from object's origin (world position)
426
+ obj_origin = obj.matrix_world.translation
427
+
428
+ # Calculate min/max displacement in each direction from object's origin
429
+ min_displacement = Vector((
430
+ min_x - obj_origin.x, # Furthest extent in negative x direction
431
+ min_y - obj_origin.y, # Furthest extent in negative y direction
432
+ min_z - obj_origin.z # Furthest extent in negative z direction
433
+ ))
434
+
435
+ max_displacement = Vector((
436
+ max_x - obj_origin.x, # Furthest extent in positive x direction
437
+ max_y - obj_origin.y, # Furthest extent in positive y direction
438
+ max_z - obj_origin.z # Furthest extent in positive z direction
439
+ ))
440
+
441
+ return {
442
+ "min": min_bound,
443
+ "max": max_bound,
444
+ "size": max_bound - min_bound,
445
+ "displacement": {
446
+ "min": min_displacement,
447
+ "max": max_displacement
448
+ }
449
+ }
450
+
451
+ def _choose_surface_weighted_by_area(self):
452
+ """Choose a surface randomly, weighted by area."""
453
+ if not self.surfaces:
454
+ return None
455
+
456
+ # Create weighted list based on areas
457
+ surface_names = list(self.surfaces.keys())
458
+ areas = [self.surfaces[name]["area"] for name in surface_names]
459
+
460
+ # Use random.choices for weighted selection
461
+ chosen_surface = random.choices(surface_names, weights=areas, k=1)[0]
462
+ return chosen_surface
463
+
464
+ def _check_collision_on_surface(self, obj_bounds, surface_name, safety_margin=0.01):
465
+ """Check if object bounds would collide with existing objects on surface."""
466
+ placed_objects = self.placed_objects[surface_name]
467
+
468
+ for existing_bounds in placed_objects:
469
+ # Check for bounding box overlap with safety margin
470
+ if (obj_bounds["min"].x - safety_margin < existing_bounds["max"].x and
471
+ obj_bounds["max"].x + safety_margin > existing_bounds["min"].x and
472
+ obj_bounds["min"].y - safety_margin < existing_bounds["max"].y and
473
+ obj_bounds["max"].y + safety_margin > existing_bounds["min"].y):
474
+ return True # Collision detected
475
+
476
+ return False # No collision
477
+
478
+ def place(self, object_name, max_attempts=1000, safety_margin=0.01):
479
+ """
480
+ Place an object on one of the surfaces.
481
+
482
+ Args:
483
+ object_name: Name of the object to place
484
+ max_attempts: Maximum number of placement attempts
485
+ safety_margin: Minimum distance from other objects
486
+
487
+ Returns:
488
+ bool: True if placement was successful, False otherwise
489
+ """
490
+ obj_to_place = bpy.data.objects[object_name]
491
+
492
+ # Get object bounds after transformation
493
+ obj_bounds = self._get_object_bounds(obj_to_place)
494
+ obj_size = obj_bounds["size"]
495
+
496
+ # Calculate the bottom offset (distance from object center to bottom)
497
+ obj_bottom_offset = obj_bounds["displacement"]["min"].z
498
+
499
+ # Try to place the object
500
+ for attempt in range(max_attempts):
501
+ surface_name = self._choose_surface_weighted_by_area()
502
+
503
+ surface_info = self.surfaces[surface_name]
504
+ surface_bounds = surface_info["bounds"]
505
+ z_level = surface_info["z_level"]
506
+
507
+ # Calculate minimum/maximum x and y coordinates that would place the object
508
+ # within the surface
509
+ min_x = surface_bounds["min"].x - obj_bounds["displacement"]["min"].x
510
+ max_x = surface_bounds["max"].x - obj_bounds["displacement"]["max"].x
511
+ min_y = surface_bounds["min"].y - obj_bounds["displacement"]["min"].y
512
+ max_y = surface_bounds["max"].y - obj_bounds["displacement"]["max"].y
513
+
514
+ if min_x > max_x or min_y > max_y:
515
+ # Object does not fit on surface
516
+ print("Object does not fit on surface.")
517
+ continue
518
+
519
+ # Generate random position within surface bounds
520
+ random_x = random.uniform(min_x, max_x)
521
+ random_y = random.uniform(min_y, max_y)
522
+
523
+ # Calculate final position (bottom of object touches surface)
524
+ final_position = Vector((random_x, random_y, z_level - obj_bottom_offset))
525
+
526
+ # Move object to test position
527
+ obj_to_place.location = final_position
528
+ bpy.context.view_layer.update()
529
+
530
+ # Get bounds at new position
531
+ new_bounds = self._get_object_bounds(obj_to_place)
532
+
533
+ # Check for collisions with existing objects on this surface
534
+ if not self._check_collision_on_surface(new_bounds, surface_name, safety_margin):
535
+ # Successful placement!
536
+ self.placed_objects[surface_name].append(new_bounds)
537
+ print(f"Object '{object_name}' placed on '{surface_name}' at {final_position}")
538
+ print(f"obj_bottom_offset={obj_bottom_offset}")
539
+ return (final_position.x, final_position.y, final_position.z)
540
+
541
+ # Failed to place after max attempts
542
+ print(f"Failed to place object '{object_name}' after {max_attempts} attempts")
543
+ return None
544
+
545
+ def prepare_instance(object_counts):
546
+ """Prepare an instance by setting up the kitchen environment and camera."""
547
+ hide_all(object_counts)
548
+ instance_data = {}
549
+
550
+ kitchen_number = random.randint(1, object_counts["n_kitchens"])
551
+ instance_data["kitchen_number"] = kitchen_number
552
+ kitchen_name = f"Kitchen {kitchen_number}"
553
+ bpy.data.collections[kitchen_name].hide_render = False
554
+ vlayer = bpy.context.scene.view_layers["ViewLayer"]
555
+ vlayer.layer_collection.children["Kitchens"].children[kitchen_name].hide_viewport = False
556
+
557
+ (instance_data["camera_rotation_x"],
558
+ instance_data["camera_rotation_z"],
559
+ instance_data["camera_scale"]) = set_random_camera_position(f"Kitchen {kitchen_number}")
560
+
561
+ bpy.context.scene.camera = bpy.data.objects[f"Kitchen {kitchen_number} camera"]
562
+
563
+ instance_data["floor_number"] = set_random_floor()
564
+ instance_data["wall_number"] = set_random_wall()
565
+
566
+ instance_data["light_x"], instance_data["light_y"] = set_random_light_position()
567
+ instance_data["light_power"] = set_random_light_power()
568
+ instance_data["light_colour"] = set_random_light_colour()
569
+
570
+ return instance_data
571
+
572
+ def place_ingredient(ingredient, object_counts, kitchen_surfaces):
573
+ """Place a specific ingredient on the kitchen surfaces."""
574
+ objects_placed = []
575
+ if ingredient == "Spice":
576
+ n = random.randint(1, 3)
577
+ else:
578
+ n = 1
579
+ object_numbers = random.sample(
580
+ range(1, object_counts["ingredient_counts"][ingredient] + 1), k=n)
581
+ for object_number in object_numbers:
582
+ object_data = {}
583
+
584
+ object_name = f"{ingredient} {object_number}"
585
+ object_data["object_name"] = object_name
586
+
587
+ (object_data["z_rotation"],
588
+ object_data["scale"]) = apply_random_transform(object_name)
589
+
590
+ object_data["position"] = kitchen_surfaces.place(object_name)
591
+
592
+ if object_name == "Egg 5":
593
+ object_data["egg_cap_rotation"] = set_random_egg_box_openness()
594
+
595
+ if object_data["position"] is not None:
596
+ show(bpy.data.objects[object_name])
597
+ objects_placed.append(object_data)
598
+
599
+ return objects_placed
600
+
601
+ def place_random_object(object_number, kitchen_surfaces):
602
+ """Place a random object on the kitchen surfaces."""
603
+ object_data = {}
604
+
605
+ object_name = f"Object {object_number}"
606
+ object_data["object_name"] = object_name
607
+
608
+ (object_data["z_rotation"],
609
+ object_data["scale"]) = apply_random_transform(object_name)
610
+
611
+ object_data["position"] = kitchen_surfaces.place(object_name)
612
+
613
+ if object_data["position"] is not None:
614
+ show(bpy.data.objects[object_name])
615
+ return object_data
616
+ else:
617
+ return None
618
+
619
+ def create_random_instance(object_counts):
620
+ """Create a random kitchen instance with ingredients and random objects."""
621
+ instance_data = prepare_instance(object_counts)
622
+
623
+ recipe_idx = random.randint(0, len(recipes_ordered) - 1)
624
+ instance_data["recipe_idx"] = recipe_idx
625
+ recipe_name = recipes_ordered[recipe_idx]
626
+ instance_data["recipe_name"] = recipe_name
627
+
628
+ kitchen_surfaces = Surfaces(f"Kitchen {instance_data['kitchen_number']}")
629
+
630
+ instance_data["objects"] = []
631
+
632
+ for ingredient in recipes[recipe_name]:
633
+ ingredients_to_place = []
634
+ if ingredient in ingredient_groups:
635
+ usable_group_ingredients = [i for i in ingredient_groups[ingredient] if i not in recipes[recipe_name]]
636
+ if ingredient == "Pasta":
637
+ n = 1
638
+ else:
639
+ n = random.randint(1, len(usable_group_ingredients))
640
+ ingredients_to_place.extend(random.sample(usable_group_ingredients, k=n))
641
+ else:
642
+ ingredients_to_place.append(ingredient)
643
+
644
+ for ingredient in ingredients_to_place:
645
+ instance_data["objects"].extend(place_ingredient(ingredient, object_counts, kitchen_surfaces))
646
+
647
+ n_random = random.randint(0, 3)
648
+ random_objects = random.sample(range(1, object_counts["n_random_objects"] + 1), k=n_random)
649
+ for object_number in random_objects:
650
+ object_data = place_random_object(object_number, kitchen_surfaces)
651
+ if object_data is not None:
652
+ instance_data["objects"].append(object_data)
653
+
654
+ return instance_data
655
+
656
+ def render(instance_data, save_dir, name):
657
+ """Render the kitchen instance and save the results."""
658
+ bpy.context.scene.frame_set(1)
659
+ bpy.context.scene.node_tree.nodes["File Output"].base_path = os.path.join(save_dir, "crypto")
660
+ bpy.data.scenes["Scene"].render.filepath = os.path.join(save_dir, name)
661
+ bpy.context.view_layer.update()
662
+ bpy.ops.render.render(write_still=True)
663
+ os.rename(os.path.join(save_dir, "crypto0001.exr"), os.path.join(save_dir, name + ".exr"))
664
+
665
+ with open(os.path.join(save_dir, name + ".json"), "w") as f:
666
+ json.dump(instance_data, f)
667
+
668
+ def blender_init():
669
+ """Initialize Blender with the required file and settings."""
670
+ bpy.ops.wm.open_mainfile(filepath="Kitchen Dataset.blend")
671
+
672
+ bpy.context.preferences.addons["cycles"].preferences.compute_device_type = "OPTIX"
673
+ bpy.context.preferences.addons["cycles"].preferences.refresh_devices()
674
+ bpy.context.preferences.addons["cycles"].preferences.devices["NVIDIA GeForce RTX 4090"].use = True
675
+ bpy.context.scene.cycles.device = "GPU"
676
+
677
+ def generate_examples(dir, first_number, last_number, object_counts, filename_length=0):
678
+ """Generate a series of kitchen instances and render them."""
679
+ filename_length = max(filename_length, len(str(last_number)))
680
+ dir.mkdir(parents=True, exist_ok=True)
681
+ for i in trange(first_number, last_number + 1):
682
+ instance_data = create_random_instance(object_counts)
683
+ render(instance_data, str(dir.resolve()), str(i).zfill(filename_length))
684
+
685
+ def create(train_size, val_size, test_size, dataset_dir):
686
+ """Create a complete dataset with training, validation, and test sets."""
687
+ blender_init()
688
+ object_counts = count_objects()
689
+
690
+ dataset_info = {
691
+ "train_size": train_size,
692
+ "val_size": val_size,
693
+ "test_size": test_size,
694
+ "object_counts": object_counts,
695
+ "ingredient_groups": ingredient_groups,
696
+ "recipes": recipes
697
+ }
698
+
699
+ dataset_dir.mkdir(parents=True)
700
+ with (dataset_dir / "info.json").open(mode="w") as f:
701
+ json.dump(dataset_info, f)
702
+
703
+ folders = [dataset_dir / "train", dataset_dir / "val", dataset_dir / "test"]
704
+ sizes = [train_size, val_size, test_size]
705
+
706
+ for folder, size in list(zip(folders, sizes)):
707
+ generate_examples(folder, 1, size, object_counts=object_counts)
708
+
709
+ def print_ingredient_distribution(dir):
710
+ """Print the distribution of ingredients in the generated dataset."""
711
+ ingredient_counts = {ingredient: 0 for ingredient in ingredients}
712
+ total_instances = 0
713
+
714
+ for file in dir.glob("*.json"):
715
+ total_instances += 1
716
+ already_counted = set()
717
+ with file.open() as f:
718
+ instance_data = json.load(f)
719
+ for obj in instance_data["objects"]:
720
+ ingredient_name = obj["object_name"].rsplit(" ", 1)[0]
721
+ if ingredient_name in ingredient_counts and ingredient_name not in already_counted:
722
+ ingredient_counts[ingredient_name] += 1
723
+ already_counted.add(ingredient_name)
724
+
725
+ print("Ingredient distribution:")
726
+ for ingredient, count in sorted(ingredient_counts.items(), key=lambda x: x[1], reverse=True):
727
+ print(f"{ingredient}: {count} ({(count / total_instances) * 100:.2f}%)")
728
+
729
+ if __name__ == "__main__":
730
+ args = parse_args()
731
+
732
+ if args.command == "create":
733
+ create(args.train_size, args.val_size, args.test_size, args.dataset_dir)
734
+ elif args.command == "generate_examples":
735
+ blender_init()
736
+ object_counts = count_objects()
737
+ generate_examples(args.dir, args.first_number, args.last_number, object_counts, args.filename_length)
738
+ elif args.command == "ingredient_distribution":
739
+ print_ingredient_distribution(args.dir)