1
$\begingroup$

I need to export vertex colors from Blender to a custom mesh format. To do it, I need to create a dictionary where the vertex index is a key and color is a value, as proof of concept I wrote this but it's extremely inefficient. How can this be implemented better?

def _get_vertex_colors(blender_mesh):
    mesh = blender_mesh.data
    colors = {}
    try:
        color_layer = mesh.vertex_colors[0]
    except:
        return colors
    for poly in mesh.polygons:
        for loop_index in poly.loop_indices:
            b = round(color_layer.data[loop_index].color[0]*255)
            g = round(color_layer.data[loop_index].color[1]*255)
            r = round(color_layer.data[loop_index].color[2]*255)
            a = round(color_layer.data[loop_index].color[3]*255)
            colors[mesh.loops[loop_index].vertex_index] = (r,g,b,a)
    return colors
$\endgroup$
2
  • $\begingroup$ Hello, what version of Blender are you using ? $\endgroup$
    – Gorgious
    Commented Apr 7, 2023 at 7:37
  • $\begingroup$ Hi, version is 3.1 $\endgroup$ Commented Apr 7, 2023 at 7:48

1 Answer 1

0
$\begingroup$

My friend helped to get rig the nested loop and this reduced the execution time of the function in extreme cases from 0.5 to 0.3 seconds

def _get_vertex_colors(blender_mesh):
    mesh = blender_mesh.data
    colors = {}
    try:
        color_layer = mesh.vertex_colors[0]
    except:
        return colors
    mesh_loops = {li: loop.vertex_index for li, loop in enumerate(mesh.loops)}
    vtx_colors = {mesh_loops[li]: data.color for li, data in color_layer.data.items()}
    for idx, color in vtx_colors.items():
        b = round(color[0]*255)
        g = round(color[1]*255)
        r = round(color[2]*255)
        a = round(color[3]*255)
        colors[idx] = (r,g,b,a)
    return colors
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .