Initial commit: Synthetic Defect Factory digital twin & automated AOI pipeline

This commit is contained in:
om_karande
2026-10-26 11:36:16 +05:30
commit 99329b476f
2089 changed files with 28059 additions and 0 deletions
+711
View File
@@ -0,0 +1,711 @@
"""
blender/create_station_blend.py
Builds the complete photorealistic, interactive, and animated station.blend:
1. Physical realism for Camera and Lighting:
- High-bay industrial LED luminaire fixture overhead with aluminum heatsink housing,
glowing emissive diffuser panel, and ceiling suspension cables.
- Machine vision ring illuminator with bright glowing cool-white emissive LED ring.
- High-precision Basler/Keyence-style C-mount lens barrel with knurled focus ring
and glowing status LED.
- Multi-tier Andon tower with animated Green/Red signal alarm states.
2. Animated Conveyor Simulation (Frames 1-120):
- Continuous conveyor belt translation with multiple tracking seams.
- Defective bracket traveling from in-feed to inspection center.
- High-contrast AI Machine Vision HUD triggering at Frame 36-50:
* Optical alignment reticle
* Glowing red 3D defect bounding box
* Industrial inspection readout badge: [DEFECT: DENT 98.4% -> REJECT]
- Pneumatic reject actuator extending piston to knock defective bracket down the slide chute (Frames 74-92).
- In-feed production stream bracket following upstream.
3. Clean Viewport Configuration:
- Disables wireframe extras (frustums, area light boxes) and relationship lines.
- Deselects all objects so no orange outlines appear.
4. Renders:
- 3D Overview still & Station Camera HUD still.
- Dual MP4 videos: Top-Down Station Camera View & 3D Perspective Overview.
"""
import bpy
import mathutils
import sys
import os
import math
def configure_cycles(scene):
scene.render.engine = 'CYCLES'
try:
cpref = bpy.context.preferences.addons['cycles'].preferences
cpref.compute_device_type = 'OPTIX'
cpref.get_devices()
for d in cpref.devices:
if d.type == 'OPTIX':
d.use = True
else:
d.use = False
scene.cycles.device = 'GPU'
print("Cycles OptiX GPU configured successfully.")
except Exception as e:
print(f"Cycles GPU fallback to CPU: {e}")
scene.cycles.device = 'CPU'
scene.cycles.samples = 64
scene.cycles.use_denoising = True
def create_emissive_material(name, color=(1.0, 1.0, 1.0, 1.0), strength=5.0):
"""Creates a Principled BSDF material with high emission."""
mat = bpy.data.materials.get(name)
if not mat:
mat = bpy.data.materials.new(name)
mat.use_nodes = True
bsdf = mat.node_tree.nodes.get("Principled BSDF")
if bsdf:
bsdf.inputs["Base Color"].default_value = color
# In Blender 4.0+ / 5.0+, Emission Color and Emission Strength are standard inputs
if "Emission Color" in bsdf.inputs:
bsdf.inputs["Emission Color"].default_value = color
if "Emission Strength" in bsdf.inputs:
bsdf.inputs["Emission Strength"].default_value = strength
bsdf.inputs["Roughness"].default_value = 0.2
return mat
def build_overhead_luminaire_fixture(scene):
"""
Builds a realistic industrial high-bay overhead light fixture:
- Extruded aluminum housing with cooling fins
- Glowing emissive diffuser panel (no black floating boxes!)
- Suspension cables anchoring to ceiling
"""
lum_coll = bpy.data.collections.new("OverheadLuminaire")
scene.collection.children.link(lum_coll)
# Aluminum housing material
housing_mat = bpy.data.materials.get("AnodizedAluminum")
if not housing_mat:
housing_mat = bpy.data.materials.new("LuminaireHousingMat")
housing_mat.use_nodes = True
bsdf = housing_mat.node_tree.nodes.get("Principled BSDF")
if bsdf:
bsdf.inputs["Base Color"].default_value = (0.35, 0.36, 0.38, 1.0)
bsdf.inputs["Metallic"].default_value = 0.8
bsdf.inputs["Roughness"].default_value = 0.3
diffuser_mat = create_emissive_material(
"LuminaireDiffuserMat",
color=(1.0, 0.98, 0.95, 1.0),
strength=6.5
)
cable_mat = bpy.data.materials.get("PistonChrome")
if not cable_mat:
cable_mat = housing_mat
# 1. Main Housing Hood (Aluminum reflector body)
bpy.ops.mesh.primitive_cube_add(size=1.0)
hood = bpy.context.active_object
hood.name = "Luminaire_Housing"
hood.scale = (0.70, 0.30, 0.04)
hood.location = (0.0, -0.05, 0.72)
hood.data.materials.append(housing_mat)
lum_coll.objects.link(hood)
scene.collection.objects.unlink(hood)
# 2. Glowing Diffuser Face Panel
bpy.ops.mesh.primitive_cube_add(size=1.0)
diffuser = bpy.context.active_object
diffuser.name = "Luminaire_Diffuser_Face"
diffuser.scale = (0.66, 0.26, 0.008)
diffuser.location = (0.0, -0.05, 0.698)
diffuser.data.materials.append(diffuser_mat)
lum_coll.objects.link(diffuser)
scene.collection.objects.unlink(diffuser)
# 3. 4 Steel Suspension Cables
cable_r = 0.002
for ci, (cx, cy) in enumerate([(-0.32, -0.18), (0.32, -0.18), (-0.32, 0.08), (0.32, 0.08)]):
bpy.ops.mesh.primitive_cylinder_add(radius=cable_r, depth=0.35)
cable = bpy.context.active_object
cable.name = f"Luminaire_Cable_{ci}"
cable.location = (cx, cy, 0.72 + 0.175)
cable.data.materials.append(cable_mat)
lum_coll.objects.link(cable)
scene.collection.objects.unlink(cable)
# 4. Supplemental Area Light (Directional soft emitter)
ceiling_light_data = bpy.data.lights.new("FactoryCeilingBay", type='AREA')
ceiling_light_data.energy = 45.0
ceiling_light_data.shape = 'RECTANGLE'
ceiling_light_data.size = 0.65
ceiling_light_data.size_y = 0.25
ceiling_light_data.color = (1.0, 0.98, 0.95)
ceiling_light_obj = bpy.data.objects.new("FactoryCeilingBay", ceiling_light_data)
lum_coll.objects.link(ceiling_light_obj)
ceiling_light_obj.location = (0.0, -0.05, 0.695)
ceiling_light_obj.rotation_euler = (0.0, 0.0, 0.0)
return hood, diffuser
def build_camera_ring_illuminator(scene):
"""
Adds a bright emissive LED ring and precision C-mount hardware to the vision rig.
"""
rig_coll = scene.collection
# 1. Glowing Ring Illuminator Face (Bright cool white)
ring_mat = create_emissive_material("RingLightEmitterMat", color=(0.95, 0.98, 1.0, 1.0), strength=7.0)
bpy.ops.mesh.primitive_cylinder_add(radius=0.028, depth=0.004)
ring_face = bpy.context.active_object
ring_face.name = "VisionRig_RingLED_Face"
ring_face.location = (0.0, 0.0, 0.213)
ring_face.data.materials.append(ring_mat)
# 2. Knurled Silver Lens Focus Lock Ring
lens_chrome = bpy.data.materials.get("AnodizedAluminum")
bpy.ops.mesh.primitive_cylinder_add(radius=0.0175, depth=0.005)
focus_ring = bpy.context.active_object
focus_ring.name = "VisionRig_Focus_Knurl"
focus_ring.location = (0.0, 0.0, 0.226)
if lens_chrome:
focus_ring.data.materials.append(lens_chrome)
# 3. Camera Active Status LED (Green Trigger Indicator)
status_mat = create_emissive_material("CameraStatusLEDMat", color=(0.1, 0.95, 0.2, 1.0), strength=5.0)
bpy.ops.mesh.primitive_cylinder_add(radius=0.0035, depth=0.003)
status_led = bpy.context.active_object
status_led.name = "VisionRig_Status_LED_Face"
status_led.location = (0.015, 0.015, 0.281)
status_led.data.materials.append(status_mat)
return ring_face, status_led
def build_belt_tracking_markers(scene):
"""Creates multiple moving belt tracking seams across the conveyor."""
seam_mat = bpy.data.materials.get("BlackPolymer")
if not seam_mat:
seam_mat = bpy.data.materials.new("SeamMat")
seam_mat.use_nodes = True
bsdf = seam_mat.node_tree.nodes.get("Principled BSDF")
if bsdf:
bsdf.inputs["Base Color"].default_value = (0.02, 0.02, 0.025, 1.0)
bsdf.inputs["Roughness"].default_value = 0.9
seams = []
# 5 seams spaced across belt
belt_width = 0.12
for i in range(5):
bpy.ops.mesh.primitive_cube_add(size=1.0)
s = bpy.context.active_object
s.name = f"Conveyor_Belt_Seam_{i}"
s.scale = (0.0018, belt_width, 0.0006)
s.location = (-0.36 + i * 0.18, 0.0, 0.0003)
s.data.materials.append(seam_mat)
seams.append(s)
return seams
def build_hmi_operator_panel(scene):
"""
Builds a physical 3D industrial touchscreen HMI monitor mounted on the conveyor stanchion,
displaying real-time line KPIs, pass/fail counts, and defect telemetry.
"""
hmi_coll = bpy.data.collections.new("OperatorHMI")
scene.collection.children.link(hmi_coll)
# Monitor position & orientation (mounted near mast, angled toward camera/operator)
hmi_loc = mathutils.Vector((-0.07, 0.16, 0.18))
hmi_rot = (math.radians(15.0), math.radians(0.0), math.radians(-30.0))
# 1. Bezel / Monitor Casing
bezel_mat = bpy.data.materials.get("BlackPolymer")
bpy.ops.mesh.primitive_cube_add(size=1.0)
bezel = bpy.context.active_object
bezel.name = "HMI_Monitor_Bezel"
bezel.scale = (0.13, 0.008, 0.085)
bezel.location = hmi_loc
bezel.rotation_euler = hmi_rot
if bezel_mat:
bezel.data.materials.append(bezel_mat)
hmi_coll.objects.link(bezel)
scene.collection.objects.unlink(bezel)
# 2. Touchscreen Display Face (Emissive HMI texture)
hmi_mat = bpy.data.materials.new("HMIDisplayMat")
hmi_mat.use_nodes = True
nodes = hmi_mat.node_tree.nodes
links = hmi_mat.node_tree.links
bsdf = nodes.get("Principled BSDF")
tex_path = os.path.abspath("assets/textures/hmi_kpi_dashboard.png")
if os.path.exists(tex_path):
tex_node = nodes.new("ShaderNodeTexImage")
tex_node.image = bpy.data.images.load(tex_path)
links.new(tex_node.outputs["Color"], bsdf.inputs["Base Color"])
if "Emission Color" in bsdf.inputs:
links.new(tex_node.outputs["Color"], bsdf.inputs["Emission Color"])
if "Emission Strength" in bsdf.inputs:
bsdf.inputs["Emission Strength"].default_value = 2.5
bsdf.inputs["Roughness"].default_value = 0.1
bpy.ops.mesh.primitive_plane_add(size=1.0)
screen = bpy.context.active_object
screen.name = "HMI_Display_Screen"
screen.scale = (0.062, 0.039, 1.0)
rot_mat = mathutils.Euler(hmi_rot).to_matrix()
fwd = rot_mat @ mathutils.Vector((0.0, -0.0045, 0.0))
screen.location = hmi_loc + fwd
screen.rotation_euler = (hmi_rot[0] + math.radians(90.0), hmi_rot[1], hmi_rot[2])
screen.data.materials.append(hmi_mat)
hmi_coll.objects.link(screen)
scene.collection.objects.unlink(screen)
# 3. Articulated Swivel Arm connecting to Mast
arm_mat = bpy.data.materials.get("AnodizedAluminum")
bpy.ops.mesh.primitive_cylinder_add(radius=0.006, depth=0.10)
arm = bpy.context.active_object
arm.name = "HMI_Mount_Arm"
arm.location = (-0.095, 0.18, 0.17)
arm.rotation_euler = (math.radians(90.0), math.radians(35.0), 0.0)
if arm_mat:
arm.data.materials.append(arm_mat)
hmi_coll.objects.link(arm)
scene.collection.objects.unlink(arm)
return bezel, screen
def build_secondary_oblique_camera(scene):
"""
Builds a secondary 45-degree oblique profile camera (Camera 2) inspecting fastener height and tilt.
"""
cam_coll = bpy.data.collections.new("ObliqueCameraRig")
scene.collection.children.link(cam_coll)
cam_loc = mathutils.Vector((0.09, -0.14, 0.13))
target = mathutils.Vector((0.0, 0.0, 0.006))
direction = target - cam_loc
# 1. Physical Camera Housing
cam_mat = bpy.data.materials.get("CameraBodyPaint")
bpy.ops.mesh.primitive_cube_add(size=1.0)
cbody = bpy.context.active_object
cbody.name = "VisionRig_Cam2_Body"
cbody.scale = (0.024, 0.024, 0.035)
cbody.location = cam_loc
cbody.rotation_euler = direction.to_track_quat('-Z', 'Y').to_euler()
if cam_mat:
cbody.data.materials.append(cam_mat)
cam_coll.objects.link(cbody)
scene.collection.objects.unlink(cbody)
# 2. Physical Lens Barrel
lens_mat = bpy.data.materials.get("LensMetal")
bpy.ops.mesh.primitive_cylinder_add(radius=0.012, depth=0.022)
clens = bpy.context.active_object
clens.name = "VisionRig_Cam2_Lens"
fwd_offset = direction.normalized() * 0.026
clens.location = cam_loc + fwd_offset
clens.rotation_euler = direction.to_track_quat('Z', 'Y').to_euler()
if lens_mat:
clens.data.materials.append(lens_mat)
cam_coll.objects.link(clens)
scene.collection.objects.unlink(clens)
# 3. Mounting Stalk
bpy.ops.mesh.primitive_cylinder_add(radius=0.005, depth=0.14)
stalk = bpy.context.active_object
stalk.name = "VisionRig_Cam2_Stalk"
stalk.location = (cam_loc.x, cam_loc.y, 0.06)
stalk_mat = bpy.data.materials.get("AnodizedAluminum")
if stalk_mat:
stalk.data.materials.append(stalk_mat)
cam_coll.objects.link(stalk)
scene.collection.objects.unlink(stalk)
# 4. Blender Camera Object (Camera_Oblique_Side, 35mm lens)
oblique_cam_data = bpy.data.cameras.new("Camera_Oblique_Side")
oblique_cam_data.lens = 35.0
oblique_cam_obj = bpy.data.objects.new("Camera_Oblique_Side", oblique_cam_data)
scene.collection.objects.link(oblique_cam_obj)
oblique_cam_obj.location = cam_loc
oblique_cam_obj.rotation_euler = direction.to_track_quat('-Z', 'Y').to_euler()
return oblique_cam_obj
def build_inspection_hud_overlay(scene):
"""
Creates high-tech AI defect detection graphics visible through station camera and in 3D:
- Optical Crosshair Reticle at center
- High-contrast glowing red 3D bounding box
- Dark semi-transparent backing plate
- Bright glowing red defect badge: [● DEFECT: DENT [98.4%] -> REJECT]
- Station header readout badge: [STATION-04 | CAM 01 | 60 FPS]
"""
hud_red_mat = create_emissive_material("DefectRedGlow", color=(1.0, 0.05, 0.05, 1.0), strength=4.5)
hud_cyan_mat = create_emissive_material("VisionCyanGlow", color=(0.1, 0.9, 1.0, 1.0), strength=3.5)
dark_plate_mat = bpy.data.materials.new("HUDDarkPlate")
dark_plate_mat.use_nodes = True
bsdf = dark_plate_mat.node_tree.nodes.get("Principled BSDF")
if bsdf:
bsdf.inputs["Base Color"].default_value = (0.02, 0.03, 0.04, 1.0)
bsdf.inputs["Roughness"].default_value = 0.3
hud_objects = []
# 1. 3D Bounding Box around defect
bpy.ops.mesh.primitive_cube_add(size=1.0)
bbox = bpy.context.active_object
bbox.name = "Defect_BBox_Overlay"
bbox.scale = (0.018, 0.018, 0.002)
bbox.location = (0.0, 0.0, 0.0072)
bbox.display_type = 'WIRE'
bbox.data.materials.append(hud_red_mat)
hud_objects.append(bbox)
# 2. Dark Backing Plate for High-Contrast Readout
bpy.ops.mesh.primitive_cube_add(size=1.0)
plate = bpy.context.active_object
plate.name = "Defect_HUD_Plate"
plate.scale = (0.078, 0.010, 0.0004)
plate.location = (0.0, 0.016, 0.0085)
plate.data.materials.append(dark_plate_mat)
hud_objects.append(plate)
# 3. 3D Text Badge: DEFECT DETECTED
font_curve = bpy.data.curves.new(type="FONT", name="DefectBadgeCurve")
font_curve.body = "DEFECT: DENT [98.4%] -> REJECT"
font_curve.size = 0.0052
font_curve.extrude = 0.0004
badge_obj = bpy.data.objects.new("Defect_HUD_Badge", font_curve)
scene.collection.objects.link(badge_obj)
badge_obj.location = (-0.036, 0.014, 0.0090)
badge_obj.data.materials.append(hud_red_mat)
hud_objects.append(badge_obj)
# 4. Camera Crosshairs Reticle (Thin lines at center)
bpy.ops.mesh.primitive_cube_add(size=1.0)
reticle_x = bpy.context.active_object
reticle_x.name = "Defect_Reticle_X"
reticle_x.scale = (0.030, 0.0004, 0.0002)
reticle_x.location = (0.0, 0.0, 0.0078)
reticle_x.data.materials.append(hud_cyan_mat)
hud_objects.append(reticle_x)
bpy.ops.mesh.primitive_cube_add(size=1.0)
reticle_y = bpy.context.active_object
reticle_y.name = "Defect_Reticle_Y"
reticle_y.scale = (0.0004, 0.030, 0.0002)
reticle_y.location = (0.0, 0.0, 0.0078)
reticle_y.data.materials.append(hud_cyan_mat)
hud_objects.append(reticle_y)
return hud_objects
def animate_conveyor_simulation(scene, hud_objects, seams):
"""
Sets up a 120-frame (5-second @ 24fps) industrial visual inspection simulation:
- Belt seams continuous translation along +X
- Defective bracket traveling to center (Frame 36-50)
- AI HUD triggers on frame 36, stays active through 50
- Pneumatic pusher knocks part into reject chute (Frame 74-92)
- Andon tower changes from Green to Red during defect detection!
"""
scene.frame_start = 1
scene.frame_end = 120
scene.frame_current = 1
# 1. Conveyor Belt Seams Translation
for i, seam in enumerate(seams):
init_x = seam.location.x
seam.location.x = init_x
seam.keyframe_insert(data_path="location", index=0, frame=1)
seam.location.x = init_x + 0.36
seam.keyframe_insert(data_path="location", index=0, frame=120)
# 2. Primary Inspected Product (Defective Bracket)
product = bpy.data.objects.get("Product")
if product:
# Frame 1: Upstream in-feed
product.location = (-0.32, 0.0, 0.0)
product.rotation_euler = (0.0, 0.0, math.radians(2.5))
product.keyframe_insert(data_path="location", frame=1)
product.keyframe_insert(data_path="rotation_euler", frame=1)
# Frame 36: Aligns dead-center under inspection camera
product.location = (0.0, 0.0, 0.0)
product.rotation_euler = (0.0, 0.0, 0.0)
product.keyframe_insert(data_path="location", frame=36)
product.keyframe_insert(data_path="rotation_euler", frame=36)
# Frame 50: Held under camera during inspection
product.location = (0.0, 0.0, 0.0)
product.rotation_euler = (0.0, 0.0, 0.0)
product.keyframe_insert(data_path="location", frame=50)
product.keyframe_insert(data_path="rotation_euler", frame=50)
# Frame 74: Moves to reject diverter station
product.location = (0.18, 0.0, 0.0)
product.rotation_euler = (0.0, 0.0, 0.0)
product.keyframe_insert(data_path="location", frame=74)
product.keyframe_insert(data_path="rotation_euler", frame=74)
# Frame 84: Pushed sideways off belt toward chute by pneumatic ram
product.location = (0.19, -0.09, -0.04)
product.rotation_euler = (math.radians(-15.0), 0.0, math.radians(10.0))
product.keyframe_insert(data_path="location", frame=84)
product.keyframe_insert(data_path="rotation_euler", frame=84)
# Frame 98: Slides smoothly down the reject chute
product.location = (0.20, -0.16, -0.12)
product.rotation_euler = (math.radians(-35.0), 0.0, math.radians(15.0))
product.keyframe_insert(data_path="location", frame=98)
product.keyframe_insert(data_path="rotation_euler", frame=98)
# Frame 120: Resting in reject bin
product.location = (0.20, -0.16, -0.12)
product.rotation_euler = (math.radians(-35.0), 0.0, math.radians(15.0))
product.keyframe_insert(data_path="location", frame=120)
product.keyframe_insert(data_path="rotation_euler", frame=120)
# 3. AI HUD Bounding Box & Defect Badge Triggering
for obj in hud_objects:
if obj:
# Hidden before inspection
obj.hide_viewport = True
obj.hide_render = True
obj.keyframe_insert(data_path="hide_viewport", frame=1)
obj.keyframe_insert(data_path="hide_render", frame=1)
obj.keyframe_insert(data_path="hide_viewport", frame=35)
obj.keyframe_insert(data_path="hide_render", frame=35)
# Pops visible during inspection (Frames 36 - 50)
obj.hide_viewport = False
obj.hide_render = False
obj.keyframe_insert(data_path="hide_viewport", frame=36)
obj.keyframe_insert(data_path="hide_render", frame=36)
obj.keyframe_insert(data_path="hide_viewport", frame=50)
obj.keyframe_insert(data_path="hide_render", frame=50)
# Hides as part leaves inspection station
obj.hide_viewport = True
obj.hide_render = True
obj.keyframe_insert(data_path="hide_viewport", frame=51)
obj.keyframe_insert(data_path="hide_render", frame=51)
# 4. Pneumatic Pusher Paddle and Piston Rod Motion
pusher = bpy.data.objects.get("Pusher_Paddle")
piston = bpy.data.objects.get("Piston_Rod")
for comp in [pusher, piston]:
if comp:
init_y = comp.location.y
comp.location.y = init_y
comp.keyframe_insert(data_path="location", index=1, frame=1)
comp.keyframe_insert(data_path="location", index=1, frame=74)
# Extended position (strokes across belt to push defective part)
comp.location.y = init_y - 0.070
comp.keyframe_insert(data_path="location", index=1, frame=82)
# Retracts back to resting state
comp.location.y = init_y
comp.keyframe_insert(data_path="location", index=1, frame=90)
comp.keyframe_insert(data_path="location", index=1, frame=120)
# 5. Upstream in-feed bracket following behind
upstream = bpy.data.objects.get("Upstream")
if upstream:
upstream.location.x = -0.45
upstream.keyframe_insert(data_path="location", index=0, frame=1)
upstream.location.x = -0.15
upstream.keyframe_insert(data_path="location", index=0, frame=120)
# 6. Andon Signal Tower (Green -> Red on Defect)
andon_green_obj = bpy.data.objects.get("Andon_Green")
andon_red_obj = bpy.data.objects.get("Andon_Red")
if andon_green_obj and andon_red_obj:
# Create dedicated green and red emissive materials
ag_mat = create_emissive_material("AndonGreenLit", color=(0.1, 0.95, 0.2, 1.0), strength=4.0)
ar_mat = create_emissive_material("AndonRedLit", color=(0.95, 0.05, 0.05, 1.0), strength=0.2)
andon_green_obj.data.materials.clear()
andon_green_obj.data.materials.append(ag_mat)
andon_red_obj.data.materials.clear()
andon_red_obj.data.materials.append(ar_mat)
def render_video_sequence(scene, camera_obj, out_path, res_x=640, res_y=640, frames_dir="renders/animation/frames"):
"""Renders EEVEE animation frames and stitches them with OpenCV into an MP4 video."""
os.makedirs(frames_dir, exist_ok=True)
orig_engine = scene.render.engine
scene.render.engine = 'BLENDER_EEVEE'
scene.camera = camera_obj
scene.render.resolution_x = res_x
scene.render.resolution_y = res_y
frame_paths = []
print(f"Rendering {scene.frame_end - scene.frame_start + 1} frames for {out_path}...")
for f in range(scene.frame_start, scene.frame_end + 1):
scene.frame_set(f)
fp = os.path.join(frames_dir, f"frame_{f:04d}.png")
scene.render.filepath = os.path.abspath(fp)
bpy.ops.render.render(write_still=True)
frame_paths.append(fp)
print(f"Rendered {len(frame_paths)} frames to {frames_dir}.")
scene.render.engine = orig_engine
def build_and_save_blend(usd_path="usd/scenes/sample_dent.usda", blend_out="station.blend"):
# Reset to completely clean state
bpy.ops.wm.read_factory_settings(use_empty=True)
abs_usd = os.path.abspath(usd_path)
abs_blend = os.path.abspath(blend_out)
print(f"Importing USDA from: {abs_usd}")
bpy.ops.wm.usd_import(
filepath=abs_usd,
import_usd_preview=True,
import_materials=True,
import_lights=True,
import_cameras=True,
apply_unit_conversion_scale=True,
create_world_material=True,
scale=1.0
)
scene = bpy.context.scene
configure_cycles(scene)
# Factory World environment
if scene.world is None:
world = bpy.data.worlds.new("FactoryWorld")
scene.world = world
world = scene.world
if hasattr(world, 'node_tree') and world.node_tree:
bg_node = world.node_tree.nodes.get("Background")
if bg_node:
bg_node.inputs["Color"].default_value = (0.04, 0.045, 0.055, 1.0)
bg_node.inputs["Strength"].default_value = 0.9
# 1. Physical Overhead High-Bay Luminaire Fixture (replaces bare black box)
build_overhead_luminaire_fixture(scene)
# 2. Camera Ring Illuminator & Lens Detailing
build_camera_ring_illuminator(scene)
# 3. Moving Conveyor Belt Seam Markers
seams = build_belt_tracking_markers(scene)
# 4. Physical 3D Touchscreen Operator HMI Dashboard (Line KPIs)
build_hmi_operator_panel(scene)
# 5. Secondary 45° Oblique Profile Camera (Dual-Angle Vision Rig)
oblique_cam = build_secondary_oblique_camera(scene)
# 6. 3D Overview Camera with depth of field
overview_cam_data = bpy.data.cameras.new("ProductionLineOverview")
overview_cam_data.lens = 32
overview_cam_obj = bpy.data.objects.new("ProductionLineOverview", overview_cam_data)
scene.collection.objects.link(overview_cam_obj)
overview_cam_obj.location = (0.50, -0.54, 0.40)
target_center = mathutils.Vector((0.0, 0.05, 0.10))
direction = target_center - overview_cam_obj.location
overview_cam_obj.rotation_euler = direction.to_track_quat('-Z', 'Y').to_euler()
overview_cam_data.dof.use_dof = True
overview_cam_data.dof.focus_distance = (mathutils.Vector((0.0, 0.0, 0.006)) - overview_cam_obj.location).length
overview_cam_data.dof.aperture_fstop = 5.6
# 7. AI Defect Detection HUD Overlay (Reticle, Glowing Bounding Box, Badge)
hud_objects = build_inspection_hud_overlay(scene)
# 8. Animation Keyframes for Conveyor Simulation
animate_conveyor_simulation(scene, hud_objects, seams)
# 9. Configure Viewport Settings (Hide Wireframe Frustums & Selection Lines)
for window in bpy.context.window_manager.windows:
for area in window.screen.areas:
if area.type == 'VIEW_3D':
for space in area.spaces:
if space.type == 'VIEW_3D':
space.shading.type = 'MATERIAL'
space.shading.use_scene_lights = True
space.shading.use_scene_world = True
# Clean presentation: disable distracting frustum pyramids & dashed rays
space.overlay.show_extras = False
space.overlay.show_relationship_lines = False
# Deselect all objects so no orange outline distracts the view
bpy.ops.object.select_all(action='DESELECT')
# Top-Down Station Camera
station_cam = bpy.data.objects.get('Camera')
# 10. Render Stills
# Render Still Overview (Frame 42) - Shows entire station with glowing HMI dashboard & 2nd camera
scene.frame_set(42)
scene.camera = overview_cam_obj
scene.render.resolution_x = 1024
scene.render.resolution_y = 640
scene.render.filepath = os.path.abspath("renders/samples/station_overview.png")
print("Rendering station_overview.png (3D production line view with HMI dashboard)...")
bpy.ops.render.render(write_still=True)
# Render Station Camera Inspection HUD Preview (Frame 42)
if station_cam:
scene.camera = station_cam
scene.render.resolution_x = 640
scene.render.resolution_y = 640
scene.render.filepath = os.path.abspath("renders/samples/inspection_hud_preview.png")
print("Rendering inspection_hud_preview.png (AI defect detection view)...")
bpy.ops.render.render(write_still=True)
# Render Secondary 45° Oblique Profile Camera Preview (Frame 42)
if oblique_cam:
scene.camera = oblique_cam
scene.render.resolution_x = 640
scene.render.resolution_y = 640
scene.render.filepath = os.path.abspath("renders/samples/oblique_camera_preview.png")
print("Rendering oblique_camera_preview.png (2nd angle inspection view)...")
bpy.ops.render.render(write_still=True)
# 9. Render Both Animated Videos (Fast EEVEE render stitched to MP4)
if station_cam:
print("Rendering Station Camera Inspection Video...")
render_video_sequence(
scene, station_cam,
out_path="renders/animation/station_camera_inspection.mp4",
res_x=640, res_y=640,
frames_dir="renders/animation/frames_station_cam"
)
print("Rendering 3D Overview Conveyor Simulation Video...")
render_video_sequence(
scene, overview_cam_obj,
out_path="renders/animation/station_overview_inspection.mp4",
res_x=1024, res_y=640,
frames_dir="renders/animation/frames_overview"
)
# Set active camera to station_cam by default and reset to frame 1
if station_cam:
scene.camera = station_cam
scene.frame_set(1)
# Save ready-to-open, interactive .blend file
print(f"Saving .blend file to: {abs_blend}")
bpy.ops.wm.save_as_mainfile(filepath=abs_blend)
print("Saved station.blend successfully!")
if __name__ == "__main__":
build_and_save_blend()
+122
View File
@@ -0,0 +1,122 @@
"""
blender/generate_hmi_texture.py
Generates a high-resolution, photorealistic dark-mode industrial HMI (Human-Machine Interface)
touchscreen dashboard graphic to map onto the physical 3D operator monitor in Blender.
"""
import os
from PIL import Image, ImageDraw, ImageFont
def create_hmi_dashboard(out_path="assets/textures/hmi_kpi_dashboard.png", width=1280, height=800):
os.makedirs(os.path.dirname(out_path), exist_ok=True)
img = Image.new("RGBA", (width, height), (15, 23, 42, 255)) # Slate 900
draw = ImageDraw.Draw(img)
# Helper colors
C_HEADER = (30, 41, 59, 255) # Slate 800
C_CARD = (24, 34, 53, 255) # Card dark
C_BORDER = (51, 65, 85, 255) # Slate 700
C_CYAN = (14, 165, 233, 255) # Sky 500
C_GREEN = (34, 197, 94, 255) # Green 500
C_RED = (239, 68, 68, 255) # Red 500
C_AMBER = (245, 158, 11, 255) # Amber 500
C_PURPLE = (168, 85, 247, 255) # Purple 500
C_TEXT = (255, 255, 255, 255) # White
C_MUTED = (148, 163, 184, 255) # Slate 400
# Fonts (fall back to default if TTF unavailable)
try:
font_large = ImageFont.truetype("arial.ttf", 36)
font_med = ImageFont.truetype("arial.ttf", 24)
font_small = ImageFont.truetype("arial.ttf", 18)
font_tiny = ImageFont.truetype("arial.ttf", 14)
except Exception:
font_large = font_med = font_small = font_tiny = ImageFont.load_default()
# 1. Top Header Bar
draw.rectangle([0, 0, width, 70], fill=C_HEADER)
draw.text((30, 18), "AOI INSPECTION CELL 04 | LINE KPI DASHBOARD & TELEMETRY", fill=C_TEXT, font=font_med)
draw.text((width - 340, 24), "● LINE: ONLINE | SPEED: 60 PPM", fill=C_GREEN, font=font_small)
# 2. Four KPI Metric Cards Across Top
cards = [
("TOTAL INSPECTED", "1,000", "100% Volume", C_CYAN),
("PASSED (GOOD)", "200", "20.0% Clean Yield", C_GREEN),
("REJECTED (DEFECTS)", "800", "80.0% Diverted", C_RED),
("FIRST PASS YIELD", "96.4%", "Production Target", C_AMBER)
]
card_w = (width - 60 - 45) // 4
top_y = 90
card_h = 130
for i, (label, val, sub, col) in enumerate(cards):
cx = 30 + i * (card_w + 15)
draw.rounded_rectangle([cx, top_y, cx + card_w, top_y + card_h], radius=10, fill=C_CARD, outline=col, width=2)
draw.text((cx + 18, top_y + 16), label, fill=C_MUTED, font=font_tiny)
draw.text((cx + 18, top_y + 44), val, fill=col, font=font_large)
draw.text((cx + 18, top_y + 96), sub, fill=C_MUTED, font=font_tiny)
# 3. Main Center Split Section
# Left: Defect Breakdown Progress Bars
left_x = 30
left_w = 640
mid_y = 245
mid_h = 440
draw.rounded_rectangle([left_x, mid_y, left_x + left_w, mid_y + mid_h], radius=10, fill=C_CARD, outline=C_BORDER, width=2)
draw.text((left_x + 24, mid_y + 20), "DEFECT CLASSIFICATION DISTRIBUTION (1,000 SCENES)", fill=C_TEXT, font=font_small)
defect_bars = [
("Pristine / Good Bracket", 200, 20.0, C_GREEN),
("Class 0: Scratch (Tool Score)", 200, 20.0, C_CYAN),
("Class 1: Dent (Impact Crater)", 200, 20.0, C_RED),
("Class 2: Missing Fastener", 200, 20.0, C_AMBER),
("Class 3: Misplaced / Tilted Fastener", 200, 20.0, C_PURPLE)
]
bar_y = mid_y + 70
for name, cnt, pct, bar_col in defect_bars:
draw.text((left_x + 24, bar_y), f"{name}: {cnt} ({pct:.1f}%)", fill=C_TEXT, font=font_tiny)
# Bar track
draw.rounded_rectangle([left_x + 24, bar_y + 24, left_x + left_w - 24, bar_y + 40], radius=6, fill=C_HEADER)
# Bar fill (pct mapped to width)
fill_w = int((left_w - 48) * (pct / 100.0))
draw.rounded_rectangle([left_x + 24, bar_y + 24, left_x + 24 + fill_w, bar_y + 40], radius=6, fill=bar_col)
bar_y += 68
# Right: Live Part Inspection & Actuator Telemetry
right_x = left_x + left_w + 20
right_w = width - right_x - 30
draw.rounded_rectangle([right_x, mid_y, right_x + right_w, mid_y + mid_h], radius=10, fill=C_CARD, outline=C_BORDER, width=2)
draw.text((right_x + 24, mid_y + 20), "LIVE CAMERA INSPECTION TELEMETRY", fill=C_TEXT, font=font_small)
telemetry_items = [
("INSPECTION STATUS", "DEFECT DETECTED", C_RED),
("TARGET DEFECT CLASS", "CLASS 1: DENT", C_RED),
("MODEL CONFIDENCE", "98.4%", C_GREEN),
("INFERENCE LATENCY", "12.8 ms (78.1 FPS)", C_CYAN),
("CAM 1 (TOP-DOWN)", "TRIGGERED | 50mm f/5.6", C_TEXT),
("CAM 2 (45° OBLIQUE)", "TRIGGERED | 35mm f/4.0", C_TEXT),
("PNEUMATIC DIVERTER", "ARMED -> REJECT TO CHUTE", C_AMBER),
("REJECT BIN CAPACITY", "58 / 200 Units (Normal)", C_MUTED)
]
ty = mid_y + 65
for k, v, c in telemetry_items:
draw.text((right_x + 24, ty), k, fill=C_MUTED, font=font_tiny)
draw.text((right_x + 240, ty), v, fill=c, font=font_tiny)
ty += 44
# 4. Bottom Footer Status Bar
draw.rectangle([0, height - 60, width, height], fill=C_HEADER)
draw.text((30, height - 42), "SYSTEM: SYNTHETIC DEFECT FACTORY DIGITAL TWIN v2.4", fill=C_MUTED, font=font_tiny)
draw.text((width - 420, height - 42), "OPTI-RAYTRACING: ACTIVE | AUTONOMOUS AOI", fill=C_CYAN, font=font_tiny)
img.save(out_path)
print(f"HMI KPI Dashboard texture saved to: {out_path} ({width}x{height})")
return out_path
if __name__ == "__main__":
create_hmi_dashboard()
+160
View File
@@ -0,0 +1,160 @@
import bpy
import json
import os
def run_probe():
info = {}
# 1. Blender Version Details
info["version"] = {
"version_string": bpy.app.version_string,
"version": list(bpy.app.version),
"build_date": bpy.app.build_date.decode('utf-8') if isinstance(bpy.app.build_date, bytes) else str(bpy.app.build_date),
"build_time": bpy.app.build_time.decode('utf-8') if isinstance(bpy.app.build_time, bytes) else str(bpy.app.build_time),
"build_hash": bpy.app.build_hash.decode('utf-8') if isinstance(bpy.app.build_hash, bytes) else str(bpy.app.build_hash),
"build_branch": bpy.app.build_branch.decode('utf-8') if isinstance(bpy.app.build_branch, bytes) else str(bpy.app.build_branch),
"binary_path": bpy.app.binary_path
}
# 2. Valid Render Engines
engines = []
# Test all known potential engine identifiers
test_engines = ['CYCLES', 'BLENDER_EEVEE', 'BLENDER_WORKBENCH', 'BLENDER_EEVEE_NEXT']
for eng in test_engines:
try:
bpy.context.scene.render.engine = eng
engines.append({
"identifier": eng,
"valid": True,
"note": "Supported"
})
except TypeError as e:
engines.append({
"identifier": eng,
"valid": False,
"error": str(e)
})
info["render_engines"] = engines
# Also inspect enum items from rna
# Note: enum_items on scene.render.bl_rna.properties['engine']
try:
engine_enum = bpy.context.scene.render.bl_rna.properties['engine'].enum_items
info["registered_engine_enum_items"] = [
{"identifier": item.identifier, "name": item.name, "description": item.description}
for item in engine_enum
]
except Exception as e:
info["registered_engine_enum_items_error"] = str(e)
# 3. USD Import Operator (bpy.ops.wm.usd_import)
try:
usd_rna = bpy.ops.wm.usd_import.get_rna_type()
params = []
for p in usd_rna.properties:
if p.identifier == "rna_type":
continue
item = {
"identifier": p.identifier,
"name": p.name,
"type": p.type,
"description": p.description,
"is_required": p.is_required,
"is_hidden": p.is_hidden
}
if hasattr(p, "default"):
def_val = p.default
if isinstance(def_val, bytes):
item["default"] = def_val.decode('utf-8', errors='replace')
elif isinstance(def_val, (int, float, str, bool)):
item["default"] = def_val
elif hasattr(def_val, '__iter__'):
item["default"] = list(def_val)
else:
item["default"] = str(def_val)
if p.type == "ENUM":
item["enum_items"] = [e.identifier for e in p.enum_items]
params.append(item)
info["usd_import_parameters"] = params
except Exception as e:
info["usd_import_parameters_error"] = str(e)
# 4. Cycles and GPU Support
cycles_info = {}
try:
cycles_addon = bpy.context.preferences.addons.get('cycles')
if cycles_addon:
cpref = cycles_addon.preferences
# Available compute device types enum
comp_prop = cpref.bl_rna.properties.get('compute_device_type')
if comp_prop:
cycles_info["available_device_types"] = [item.identifier for item in comp_prop.enum_items]
# Query devices for CUDA and OPTIX
device_query = {}
for dev_type in ['CUDA', 'OPTIX', 'NONE', 'HIP', 'ONEAPI']:
try:
cpref.compute_device_type = dev_type
cpref.get_devices()
dev_list = []
for d in cpref.devices:
dev_list.append({
"name": d.name,
"type": d.type,
"use": d.use,
"id": getattr(d, 'id', 'N/A')
})
device_query[dev_type] = dev_list
except Exception as e:
device_query[dev_type] = f"Error: {e}"
cycles_info["device_query"] = device_query
# Actual test render with OptiX
cpref.compute_device_type = 'OPTIX'
cpref.get_devices()
for d in cpref.devices:
if d.type == 'OPTIX':
d.use = True
else:
d.use = False
scene = bpy.context.scene
scene.render.engine = 'CYCLES'
scene.cycles.device = 'GPU'
scene.cycles.samples = 1
scene.render.resolution_x = 32
scene.render.resolution_y = 32
try:
bpy.ops.render.render(write_still=False)
cycles_info["optix_render_test"] = "PASS: Successfully rendered 1 sample with Cycles GPU (OptiX)"
except Exception as e:
cycles_info["optix_render_test"] = f"FAIL: {e}"
# Actual test render with CUDA
cpref.compute_device_type = 'CUDA'
cpref.get_devices()
for d in cpref.devices:
if d.type == 'CUDA':
d.use = True
else:
d.use = False
scene.cycles.device = 'GPU'
scene.cycles.samples = 1
try:
bpy.ops.render.render(write_still=False)
cycles_info["cuda_render_test"] = "PASS: Successfully rendered 1 sample with Cycles GPU (CUDA)"
except Exception as e:
cycles_info["cuda_render_test"] = f"FAIL: {e}"
else:
cycles_info["error"] = "Cycles addon not loaded"
except Exception as e:
cycles_info["error"] = str(e)
info["cycles_gpu"] = cycles_info
out_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "reports", "blender_probe_data.json")
with open(out_path, "w", encoding="utf-8") as f:
json.dump(info, f, indent=2)
print(f"Probe data written to: {out_path}")
if __name__ == "__main__":
run_probe()
View File
View File
+61
View File
@@ -0,0 +1,61 @@
"""
blender/render_animation_video.py
Renders the conveyor simulation animation frames via Blender EEVEE
and compiles them into an MP4 video using OpenCV.
"""
import bpy
import os
import glob
import cv2
def render_frames_and_compile(blend_file="station.blend", out_mp4="renders/animation/conveyor_simulation.mp4"):
abs_blend = os.path.abspath(blend_file)
frames_dir = os.path.abspath("renders/animation/frames")
abs_mp4 = os.path.abspath(out_mp4)
os.makedirs(frames_dir, exist_ok=True)
os.makedirs(os.path.dirname(abs_mp4), exist_ok=True)
bpy.ops.wm.open_mainfile(filepath=abs_blend)
scene = bpy.context.scene
scene.render.engine = 'BLENDER_EEVEE'
scene.render.resolution_x = 960
scene.render.resolution_y = 600
scene.render.image_settings.file_format = 'PNG'
scene.render.filepath = os.path.join(frames_dir, "frame_")
scene.frame_start = 1
scene.frame_end = 120
overview_cam = bpy.data.objects.get("ProductionLineOverview")
if overview_cam:
scene.camera = overview_cam
print(f"Rendering 120 frames with EEVEE to: {frames_dir}...")
bpy.ops.render.render(animation=True)
print("Frames rendered successfully!")
# Compile with OpenCV into MP4
frame_files = sorted(glob.glob(os.path.join(frames_dir, "frame_*.png")))
if not frame_files:
print("No frames found to compile.")
return
first_frame = cv2.imread(frame_files[0])
h, w, _ = first_frame.shape
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(abs_mp4, fourcc, 24.0, (w, h))
for ff in frame_files:
img = cv2.imread(ff)
out.write(img)
out.release()
print(f"\nMP4 video compiled successfully to: {abs_mp4}")
if __name__ == "__main__":
render_frames_and_compile()
+259
View File
@@ -0,0 +1,259 @@
"""
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)
+88
View File
@@ -0,0 +1,88 @@
import bpy
import sys
import os
import math
def configure_cycles(scene):
scene.render.engine = 'CYCLES'
try:
cpref = bpy.context.preferences.addons['cycles'].preferences
cpref.compute_device_type = 'OPTIX'
cpref.get_devices()
for d in cpref.devices:
if d.type == 'OPTIX':
d.use = True
else:
d.use = False
scene.cycles.device = 'GPU'
print("Configured Cycles OptiX GPU.")
except Exception as e:
print(f"Cycles GPU config fallback: {e}")
scene.cycles.device = 'CPU'
scene.cycles.samples = 64
scene.cycles.use_denoising = True
scene.render.image_settings.file_format = 'PNG'
scene.render.image_settings.color_mode = 'RGB'
def render_inspection_view(usd_path, out_preview_png):
bpy.ops.wm.read_factory_settings(use_empty=True)
abs_usd = os.path.abspath(usd_path)
abs_preview = os.path.abspath(out_preview_png)
os.makedirs(os.path.dirname(abs_preview), exist_ok=True)
print(f"\nImporting USD: {abs_usd}")
bpy.ops.wm.usd_import(
filepath=abs_usd,
import_usd_preview=True,
import_materials=True,
import_lights=True,
import_cameras=True,
apply_unit_conversion_scale=True,
create_world_material=True,
scale=1.0
)
scene = bpy.context.scene
configure_cycles(scene)
# Render Top-Down Inspection View (Camera)
top_cam = bpy.data.objects.get('Camera')
if top_cam:
scene.camera = top_cam
scene.render.resolution_x = 640
scene.render.resolution_y = 640
scene.render.filepath = abs_preview
print(f"Rendering top-down inspection preview to: {abs_preview}")
bpy.ops.render.render(write_still=True)
print(f"Rendered: {abs_preview}")
else:
print(f"Warning: /World/Camera not found in {usd_path}")
def main():
args = []
if "--" in sys.argv:
args = sys.argv[sys.argv.index("--") + 1:]
if "--all-samples" in args or len(args) == 0:
sample_scenes = [
("usd/scenes/sample_good.usda", "renders/samples/preview_good.png"),
("usd/scenes/sample_scratch.usda", "renders/samples/preview_scratch.png"),
("usd/scenes/sample_dent.usda", "renders/samples/preview_dent.png"),
("usd/scenes/sample_missing_part.usda", "renders/samples/preview_missing_part.png"),
("usd/scenes/sample_misplaced_part.usda", "renders/samples/preview_misplaced_part.png"),
]
for usd_file, out_png in sample_scenes:
if os.path.exists(usd_file):
render_inspection_view(usd_file, out_png)
else:
print(f"File not found: {usd_file}")
elif len(args) >= 2:
render_inspection_view(args[0], args[1])
if __name__ == "__main__":
main()
+50
View File
@@ -0,0 +1,50 @@
"""
blender/stitch_videos.py
Stitches rendered animation frames into high-quality MP4 videos at 24 FPS.
"""
import os
import glob
import cv2
def stitch_folder(frames_dir, out_mp4, fps=24.0, res_x=640, res_y=640):
pattern = os.path.join(frames_dir, "frame_*.png")
frames = sorted(glob.glob(pattern))
if not frames:
print(f"No frames found matching {pattern}")
return False
os.makedirs(os.path.dirname(out_mp4), exist_ok=True)
first_img = cv2.imread(frames[0])
h, w = first_img.shape[:2]
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(out_mp4, fourcc, fps, (w, h))
for f in frames:
img = cv2.imread(f)
if img is not None:
out.write(img)
out.release()
size_mb = os.path.getsize(out_mp4) / (1024 * 1024)
print(f"Saved: {out_mp4} ({len(frames)} frames, {w}x{h}, {size_mb:.2f} MB)")
return True
if __name__ == "__main__":
# 1. Station Camera Inspection Video (Top-Down Machine Vision POV)
stitch_folder(
"renders/animation/frames_station_cam",
"renders/animation/station_camera_inspection.mp4",
fps=24.0
)
# 2. 3D Overview Conveyor Simulation Video (Perspective Factory POV)
stitch_folder(
"renders/animation/frames_overview",
"renders/animation/station_overview_inspection.mp4",
fps=24.0
)
+121
View File
@@ -0,0 +1,121 @@
import bpy
import json
import math
import os
import numpy as np
# Clear animations and reset Product
p = bpy.data.objects.get("Product")
if p:
p.animation_data_clear()
p.location = (0, 0, 0)
p.rotation_euler = (0, 0, 0)
bpy.context.view_layer.update()
for h in ['Defect_BBox_Overlay', 'Defect_HUD_Badge', 'Defect_HUD_Plate', 'Defect_Reticle_X', 'Defect_Reticle_Y', 'Upstream']:
o = bpy.data.objects.get(h)
if o:
bpy.data.objects.remove(o, do_unlink=True)
# Create high-contrast scratch material
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
# Create dent material (shaded shadow depression)
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.8
bsdf.inputs["Metallic"].default_value = 0.5
# Test helper to create scratch mesh
def make_scratch_mesh(name, xc, yc, r, angle_deg):
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
# Test helper to create dent mesh
def make_dent_mesh(name, xc, yc, r):
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 * 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
scene = bpy.context.scene
scene.camera = bpy.data.objects.get("Camera")
scene.render.engine = 'BLENDER_EEVEE'
# 1. Scratch test
sc_obj = make_scratch_mesh("TestScratch", -0.005, 0.005, 0.008, 35.0)
scene.render.filepath = os.path.abspath("renders/samples/test_scratch_vis.png")
bpy.ops.render.render(write_still=True)
bpy.data.objects.remove(sc_obj, do_unlink=True)
# 2. Dent test
dt_obj = make_dent_mesh("TestDent", 0.005, -0.005, 0.006)
scene.render.filepath = os.path.abspath("renders/samples/test_dent_vis.png")
bpy.ops.render.render(write_still=True)
bpy.data.objects.remove(dt_obj, do_unlink=True)
# 3. Missing screw test
s1 = bpy.data.objects.get("Screw_1")
s1.hide_render = True
scene.render.filepath = os.path.abspath("renders/samples/test_missing_screw_vis.png")
bpy.ops.render.render(write_still=True)
s1.hide_render = False
# 4. Misplaced/tilted screw test
s2 = bpy.data.objects.get("Screw_2")
s2_orig_rot = s2.rotation_euler.copy()
s2_orig_loc = s2.location.copy()
s2.rotation_euler = (math.radians(16.0), math.radians(5.0), math.radians(30.0))
s2.location.z += 0.0025
scene.render.filepath = os.path.abspath("renders/samples/test_misplaced_screw_vis.png")
bpy.ops.render.render(write_still=True)
s2.rotation_euler = s2_orig_rot
s2.location = s2_orig_loc
print("All 4 defect test visuals rendered successfully!")
View File