""" blender/render_dataset_batch.py Optimized Headless Batch Renderer for 1,000 Synthetic Dataset Images: - Renders 800 train images to dataset/images/train/ - Renders 200 val images to dataset/images/val/ - Applies physical defects directly from usd/manifests/scene_*.json: * Class 0: Scratch (high-contrast abrasive micro-ribbon) * Class 1: Dent (radial depression dish) * Class 2: Missing part (screw removed, bore hole exposed) * Class 3: Misplaced part (screw tilted and elevated) * Good parts: Pristine bracket with both screws seated - In-memory execution using Blender EEVEE and station.blend """ import os import sys import json import math import time import bpy import numpy as np def setup_defect_materials(): """Creates materials for scratch and dent defects.""" scratch_mat = bpy.data.materials.get("ScratchAbrasion") if not scratch_mat: scratch_mat = bpy.data.materials.new("ScratchAbrasion") scratch_mat.use_nodes = True bsdf = scratch_mat.node_tree.nodes.get("Principled BSDF") if bsdf: bsdf.inputs["Base Color"].default_value = (0.12, 0.12, 0.14, 1.0) bsdf.inputs["Roughness"].default_value = 0.95 bsdf.inputs["Metallic"].default_value = 0.4 dent_mat = bpy.data.materials.get("DentDepression") if not dent_mat: dent_mat = bpy.data.materials.new("DentDepression") dent_mat.use_nodes = True bsdf = dent_mat.node_tree.nodes.get("Principled BSDF") if bsdf: bsdf.inputs["Base Color"].default_value = (0.22, 0.22, 0.25, 1.0) bsdf.inputs["Roughness"].default_value = 0.85 bsdf.inputs["Metallic"].default_value = 0.5 return scratch_mat, dent_mat def make_scratch_mesh(name, xc, yc, r, angle_deg, scratch_mat): """Creates a thin directional abrasive scratch ribbon on the bracket top face.""" mesh = bpy.data.meshes.new(name) obj = bpy.data.objects.new(name, mesh) bpy.context.scene.collection.objects.link(obj) rad = math.radians(angle_deg) dx = math.cos(rad) * r dy = math.sin(rad) * r w = 0.0006 nx = -math.sin(rad) * w ny = math.cos(rad) * w lz = 0.0061 verts = [ (xc - dx + nx, yc - dy + ny, lz), (xc - dx - nx, yc - dy - ny, lz), (xc + dx - nx, yc + dy - ny, lz), (xc + dx + nx, yc + dy + ny, lz), ] faces = [(0, 1, 2, 3)] mesh.from_pydata(verts, [], faces) mesh.update() obj.data.materials.append(scratch_mat) return obj def make_dent_mesh(name, xc, yc, r, dent_mat): """Creates a circular indented dish on the bracket top face.""" mesh = bpy.data.meshes.new(name) obj = bpy.data.objects.new(name, mesh) bpy.context.scene.collection.objects.link(obj) verts = [(xc, yc, 0.0048)] n_seg = 16 lz = 0.0061 for i in range(n_seg): th = 2.0 * math.pi * i / n_seg verts.append((xc + r * math.cos(th), yc + r * math.sin(th), lz)) faces = [(0, i + 1, (i + 1) % n_seg + 1) for i in range(n_seg)] mesh.from_pydata(verts, [], faces) mesh.update() obj.data.materials.append(dent_mat) return obj def render_dataset(limit=None): if not bpy.data.objects.get("Camera"): bpy.ops.wm.open_mainfile(filepath=os.path.abspath("station.blend")) scene = bpy.context.scene scene.render.engine = 'BLENDER_EEVEE' scene.render.resolution_x = 640 scene.render.resolution_y = 640 top_cam = bpy.data.objects.get("Camera") if not top_cam: raise ValueError("Top-down inspection camera 'Camera' not found in scene") scene.camera = top_cam # 1. Position Product at the inspection center (0, 0, 0) and clear animation product = bpy.data.objects.get("Product") if product: product.animation_data_clear() product.location = (0.0, 0.0, 0.0) product.rotation_euler = (0.0, 0.0, 0.0) # 2. Remove HUD overlays and duplicate upstream/downstream objects for o in list(bpy.data.objects): if any(tag in o.name for tag in [".001", ".002", "Upstream", "Downstream", "Defect_BBox", "Defect_HUD", "Defect_Reticle"]): bpy.data.objects.remove(o, do_unlink=True) bpy.context.view_layer.update() # 3. Setup materials scratch_mat, dent_mat = setup_defect_materials() # 4. Cache original screw transforms screw1 = bpy.data.objects.get("Screw_1") screw2 = bpy.data.objects.get("Screw_2") s1_loc = screw1.location.copy() if screw1 else None s1_rot = screw1.rotation_euler.copy() if screw1 else None s2_loc = screw2.location.copy() if screw2 else None s2_rot = screw2.rotation_euler.copy() if screw2 else None # Directories manifests_dir = os.path.abspath("usd/manifests") train_dir = os.path.abspath("dataset/images/train") val_dir = os.path.abspath("dataset/images/val") os.makedirs(train_dir, exist_ok=True) os.makedirs(val_dir, exist_ok=True) total_scenes = 1000 if limit is None else limit train_count = int(total_scenes * 0.8) print(f"\n=======================================================") print(f"Starting Headless Batch Rendering of {total_scenes} Dataset Images") print(f" - Train: {train_count} images -> {train_dir}") print(f" - Val: {total_scenes - train_count} images -> {val_dir}") print(f"=======================================================\n") t_start = time.time() rendered_count = 0 for i in range(total_scenes): scene_id = f"scene_{i:04d}" is_train = i < train_count out_dir = train_dir if is_train else val_dir out_png = os.path.join(out_dir, f"{scene_id}.png") if os.path.exists(out_png) and os.path.getsize(out_png) > 1000: continue manifest_path = os.path.join(manifests_dir, f"{scene_id}.json") defects = [] seed = 42 + i if os.path.exists(manifest_path): with open(manifest_path, "r", encoding="utf-8") as f: mdata = json.load(f) defects = mdata.get("defects", []) seed = mdata.get("seed", seed) # Reset screws to pristine baseline if screw1: screw1.hide_render = False screw1.scale = (1.0, 1.0, 1.0) screw1.location = s1_loc.copy() screw1.rotation_euler = s1_rot.copy() if screw2: screw2.hide_render = False screw2.scale = (1.0, 1.0, 1.0) screw2.location = s2_loc.copy() screw2.rotation_euler = s2_rot.copy() # Temporary defect mesh objects to clean up after this scene temp_objs = [] # Apply each defect from manifest for d in defects: cid = d["class_id"] xc, yc, zc = d["center"] r = d["radius"] if cid == 0: # Scratch angle = (seed * 47) % 180 s_obj = make_scratch_mesh(f"Scratch_{i}", xc, yc, r, angle, scratch_mat) temp_objs.append(s_obj) elif cid == 1: # Dent d_obj = make_dent_mesh(f"Dent_{i}", xc, yc, r, dent_mat) temp_objs.append(d_obj) elif cid == 2: # Missing Screw target_prim = d.get("target_prim", "") target_screw = screw2 if "Screw_2" in target_prim else screw1 if target_screw: target_screw.hide_render = True target_screw.location = (0.0, 0.0, -10.0) target_screw.scale = (0.0001, 0.0001, 0.0001) elif cid == 3: # Misplaced / Tilted Screw target_prim = d.get("target_prim", "") target_screw = screw2 if "Screw_2" in target_prim else screw1 if target_screw: target_screw.rotation_euler = (math.radians(24.0), math.radians(8.0), math.radians(35.0)) target_screw.location.z += 0.0032 target_screw.location.x += 0.0018 bpy.context.view_layer.update() # Render frame scene.render.filepath = out_png bpy.ops.render.render(write_still=True) rendered_count += 1 # Clean up temporary defect objects for tobj in temp_objs: bpy.data.objects.remove(tobj, do_unlink=True) if (i + 1) % 50 == 0 or (i + 1) == total_scenes: elapsed = time.time() - t_start fps = rendered_count / max(0.1, elapsed) remaining = (total_scenes - (i + 1)) / max(0.01, fps) print(f"[{i+1:4d}/{total_scenes}] Rendered {rendered_count} images | " f"{fps:.2f} img/s | Elapsed: {elapsed/60:.1f}m | ETA: {remaining/60:.1f}m") # Restore pristine screws if screw1: screw1.hide_render = False screw1.location = s1_loc.copy() screw1.rotation_euler = s1_rot.copy() if screw2: screw2.hide_render = False screw2.location = s2_loc.copy() screw2.rotation_euler = s2_rot.copy() total_time = time.time() - t_start print(f"\n=======================================================") print(f"Batch rendering complete! {total_scenes} images rendered in {total_time/60:.2f} minutes.") print(f"Average speed: {total_scenes/max(0.1, total_time):.2f} images/second.") print(f"=======================================================\n") if __name__ == "__main__": limit_arg = None # Support optional limit via CLI for arg in sys.argv: if arg.startswith("--limit="): limit_arg = int(arg.split("=")[1]) render_dataset(limit=limit_arg)