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)
    bm = bmesh.new()

if not bm.loops.layers.color.get("color"):
    color_layer = bm.loops.layers.color.new("color")
    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)


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.

  • $\begingroup$ Couple of things. You are setting the color to red or red. Each time you run you are creating a new color layer. If you already have a layer you can get it from its name example blender.stackexchange.com/questions/76520/… $\endgroup$
    – batFINGER
    Commented Apr 18, 2019 at 21:28
  • $\begingroup$ Good one. Suggest rolling back question edit and making it an answer. $\endgroup$
    – batFINGER
    Commented Apr 19, 2019 at 8:33


You must log in to answer this question.

Browse other questions tagged .