Is it possible to bake textures from the command line?
This is useful for setting up batch jobs, baking an entire level for example.
Blender Stack Exchange is a question and answer site for people who use Blender to create 3D graphics, animations, or games. It only takes a minute to sign up.
Sign up to join this communityYes, the bake operator can run in background mode, for both Blender-Internal and Cycles Baking.
A very simple script could look like this:
bake.py
:
import bpy
# Like pressing the 'Bake' button in Blender
# this will remain locked until the bake is complete.
bpy.ops.object.bake(type='COMBINED')
# You might want to inspect the materials and extract images
# but for this example, simply select by name
image = bpy.data.images["Untitled"]
# save-as by setting the target path and saving
image.file_format = 'PNG'
image.filepath_raw = "//my_new_bake.png"
image.save()
Execute the bake with:
blender --background bake_test.blend --python bake.py
For batch jobs you would have to change the selection before calling bpy.ops.object.bake
each time.
This next example is more comprehensive, and uses the is_dirty
image flag to detect which images to save, giving each image a _bake
suffix.
bake_all.py
:
# Blender v2.8x +
import bpy
import os
scene = bpy.context.scene
for obj in scene.objects:
obj.select_set(False)
for obj in scene.objects:
if obj.type != 'MESH':
continue
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
bpy.ops.object.bake(type='COMBINED')
obj.select_set(False)
# save all baked images
for image in bpy.data.images:
if image.is_dirty:
# foo.png -> foo_bake.png
filepath, filepath_ext = os.path.splitext(image.filepath_raw)
image.filepath_raw = filepath + "_bake" + filepath_ext
image.save()
Execute the bake with:
blender --background bake_test.blend --python bake_all.py
Further ideas for batch baking which might be useful.
Automate baking an entire game-level:
loop over each group and bake its objects (or each group matching a naming convention, ending with .bake
for example)
Automate baking existing models:
A utility script which loads in models from an external format (OBJ, FBX, 3DS... etc), unwrap, assign images, bake and exports.
Automate low-poly mesh creation with the decimate modifier, and bake normal maps (high->low poly meshes).
Bake textures over time (create a baked image sequence).
Create a utility which runs back in a background process so you can keep on using Blender.