I'm having trouble applying vertex colors through Python to a mesh. The mesh is imported from a file which has vertex info, face info (vertex indices), and a list of colors that corresponds to each vertex.

Creating the Bmesh mesh is fine:

bm = bmesh.new()
[bm.verts.new(v) for v in verts]
[bm.faces.new([bm.verts[f[0]], bm.verts[f[1]], bm.verts[f[2]]]) for f in faces]

However, I can't seem to find a way to apply colors to each vertex. Doing

color_layer = bm.loops.layers.color.new("color")

just yields a Bmesh vertex with an index of -1...

Is there anyway to get back the correct vertex indices in this way?

import bpy
import bmesh
from random import uniform
context = bpy.context
mesh = context.object.data
bm = bmesh.new()

color_layer = bm.loops.layers.color.new("color")
# make a random color table for each vert
# vert_color = random_color_table[vert.index]
random_color_table = [[uniform(0, 1) for c in "rgb"]
                      for i in range(len(bm.verts))]
for face in bm.faces:
    for loop in face.loops:
        print("Vert:", loop.vert.index)
        loop[color_layer] = random_color_table[loop.vert.index]

Note on the generated bmesh vert indices being -1 run


which will give them enumerate order same as

for i, v in enumerate(bm.verts):
    v.index = i
  • $\begingroup$ This is great. Just to note that I received an error with the added bm.verts.index_update() at the end, but everything else worked fine. $\endgroup$ – legel Dec 5 at 17:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.