I would like to be able to set vertex colors via bpy. There are a number of answered questions including this one Set a specified vertex color to black via python for coloring the central vertex of a hexagon shape.
I have set up a scene with a subdivided mesh (2 or 3 times). I then ran the following script:
import bpy
import bmesh
from random import uniform
import mathutils
context = bpy.context
mesh = context.object.data
if mesh.is_editmode:
bm = bmesh.from_edit_mesh(mesh)
else:
bm = bmesh.new()
bm.from_mesh(mesh)
if not bm.loops.layers.color.get("color"):
color_layer = bm.loops.layers.color.new("color")
else:
color_layer = bm.loops.layers.color.get("color")
red = mathutils.Vector((1, 0, 0, 1))
black = (0, 0, 0, 1)
for face in bm.faces:
for loop in face.loops:
print("Vert:", loop.vert.index)
print("link_edges:", len(loop.vert.link_edges))
print("LOOP color:", loop[color_layer] )
loop[color_layer] = black if len(loop.vert.link_edges) == 4 else red
print("LOOP color:", loop[color_layer] )
if bm.is_wrapped:
bmesh.update_edit_mesh(mesh, False, False)
else:
bm.to_mesh(mesh)
mesh.update()
bm.clear
Thanks to the suggestions of batFINGER the script now works and changes loop colors for the vertices (there are 3 or 4 link_edges for each vertex). The results can be seen in the Texture Paint workspace by selecting Vertex Paint in the selection box.
Prior to my update of the above script the colors were not changing. I don't quite understand why it is now working - but I glad it now works.