Rendered image does not reflect changes I made by script

Hi.

I’ve used python scripts with Blender for some time now to do little things like

  • switching objects’ render visibility
  • change/rotate objects

before rendering. Never got I problem the API documentation turned me down.

But now I have a problem I can not understand:
The goal is to change material on some parts of an object. The script works as it should but the rendered image does not reflect these changes.

I attach a demo file with my script. When invoked

blender -b test.blend -P render.py

both generated images are identically. That’s wrong.

When I do

blender test.blend -P render.py

to start the GUI, I can clearly see that the script worked and the cube’s right face has been set to the blue material.
I even can press F12 to render it and the face is blue.

What do I miss?


Ok, the script cannot be attached -.- Here is it:

import bpy

def select_material_slot_by_name(material_name):
    for material_slot_index in range(len(bpy.data.objects["Cube"].material_slots)):
        if bpy.data.objects["Cube"].material_slots[material_slot_index].name == material_name:
            bpy.data.objects["Cube"].active_material_index = material_slot_index

# as is

bpy.context.scene.render.filepath = "render-as-is"
bpy.ops.render.render(animation = True)

# set material to blue

bpy.context.scene.objects.active = bpy.data.objects["Cube"]
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')

bpy.ops.object.vertex_group_set_active(group="color me")
bpy.ops.object.vertex_group_select()

select_material_slot_by_name("blue")
bpy.ops.object.material_slot_assign()

bpy.context.scene.render.filepath = "render-blue"
bpy.ops.render.render(animation = True)

I am using Blender v2.74.

Attachments

test.blend (469 KB)

Found the solution myself :slight_smile:

The API states:

When working with mesh data you may run into the problem where a script fails to run as expected in edit-mode. This is caused by edit-mode having its own data which is only written back to the mesh when exiting edit-mode.
See http://www.blender.org/api/blender_python_api_2_76_1/info_gotcha.html#modes-and-mesh-access

The solution is to put a

bpy.ops.object.mode_set(mode='OBJECT')

before calling render().