6

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.verts.ensure_lookup_table()
[bm.faces.new([bm.verts[f[0]], bm.verts[f[1]], bm.verts[f[2]]]) for f in faces]
bm.faces.ensure_lookup_table()

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

color_layer = bm.loops.layers.color.new("color")
...    
bm.faces[i].loops['color'].vert

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

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

Tom
  • 61
  • 1
  • 2

1 Answers1

8

Loop over face loops.

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

color_layer = bm.loops.layers.color.new("color")
# make a random color dict for each vert
# vert_color = random_color_table[vert]

def random_color(alpha=1):
    return [uniform(0, 1) for c in "rgb"] + [alpha]
random_color_table = {v : random_color()
                      for v in bm.verts}
for face in bm.faces:
    for loop in face.loops:
        loop[color_layer] = random_color_table[loop.vert]
bm.to_mesh(mesh)  

Should your table be indexed by vert index use something like

color_table[loop.vert.index]

If you notice that you are getting -1 for index value run

bm.verts.ensure_lookup_table()

Related

How to get random color variation on a single mesh?

set a specified vertex color to black via python

batFINGER
  • 84,216
  • 10
  • 108
  • 233
  • 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. – legel Dec 05 '19 at 17:42
  • This worked great ! Just one thing, I guess now the vertex colors expect an aplha value too, so one should replace "rgb" with "rgba" to add a 4th channel. Or just append the value 1 so the vertices stay opaque. – Gorgious Mar 13 '20 at 22:34
  • Thanks, edited. – batFINGER Mar 14 '20 at 10:03