1# based on https://github.com/DIYer22/bpycv/blob/c576e01622d87eb3534f73bf1a5686bd2463de97/example/ycb_demo.py
2import bpy
3import bpycv
4
5import os
6import glob
7import random
8
9example_data_dir = os.environ['BPY_EXAMPLE_DATA']
10
11models = sorted(glob.glob(os.path.join(example_data_dir, "model", "*", "*.obj")))
12cat_id_to_model_path = dict(enumerate(sorted(models), 1))
13
14distractors = sorted(glob.glob(os.path.join(example_data_dir, "distractor", "*.obj")))
15
16bpycv.clear_all()
17bpy.context.scene.frame_set(1)
18bpy.context.scene.render.engine = "CYCLES"
19bpy.context.scene.cycles.samples = 32
20bpy.context.scene.render.resolution_y = 1024
21bpy.context.scene.render.resolution_x = 1024
22
23# A transparency stage for holding rigid body
24stage = bpycv.add_stage(transparency=True)
25
26bpycv.set_cam_pose(cam_radius=1, cam_deg=45)
27
28hdri_dir = os.path.join(example_data_dir, "background_and_light")
29hdri_manager = bpycv.HdriManager(
30 hdri_dir=hdri_dir, download=False
31) # if download is True, will auto download .hdr file from HDRI Haven
32hdri_path = hdri_manager.sample()
33bpycv.load_hdri_world(hdri_path, random_rotate_z=True)
34
35# load 5 objects
36for index in range(5):
37 cat_id = random.choice(list(cat_id_to_model_path))
38 model_path = cat_id_to_model_path[cat_id]
39 obj = bpycv.load_obj(model_path)
40 obj.location = (
41 random.uniform(-0.2, 0.2),
42 random.uniform(-0.2, 0.2),
43 random.uniform(0.1, 0.3),
44 )
45 obj.rotation_euler = [random.uniform(-3.1415, 3.1415) for _ in range(3)]
46 # set each instance a unique inst_id, which is used to generate instance annotation.
47 obj["inst_id"] = cat_id * 1000 + index
48 with bpycv.activate_obj(obj):
49 bpy.ops.rigidbody.object_add()
50
51# load 6 distractors
52for index in range(6):
53 distractor_path = random.choice(distractors)
54 target_size = random.uniform(0.1, 0.3)
55 distractor = bpycv.load_distractor(distractor_path, target_size=target_size)
56 distractor.location = (
57 random.uniform(-0.2, 0.2),
58 random.uniform(-0.2, 0.2),
59 random.uniform(0.1, 0.3),
60 )
61 distractor.rotation_euler = [random.uniform(-3.1415, 3.1415) for _ in range(3)]
62 with bpycv.activate_obj(distractor):
63 bpy.ops.rigidbody.object_add()
64
65# run pyhsic engine for 20 frames
66for i in range(20):
67 bpy.context.scene.frame_set(bpy.context.scene.frame_current + 1)
68
69# render image, instance annoatation and depth in one line code
70result = bpycv.render_data()
71
72dataset_dir = "./dataset"
73result.save(dataset_dir=dataset_dir, fname="0", save_blend=True)
74print(f'Save to "{dataset_dir}"')
75print(f'Open "{dataset_dir}/vis/" to see visualize result.')
76