title: Blender Python How to convert a mesh with materials to vertex colors?
body: <p>I have imported objects with meshes, each having over 50 different materials, which display only a unique color, so I want get rid of the materials and use vertex colors. </p>
  
  <p>That means, each vertex of a face that has a particular material assigned will be colored to the materials main color. </p>
  
  <p>But I have issues to convert this. I cant get the faces that a material uses. This is what I have so far:</p>
  
  <pre><code>import bpy
  import bmesh
  
  for obj in bpy.context.scene.objects:       #support multiple selection
      if obj.type == 'MESH':                  #color only if mesh exists
  
          mesh = bpy.context.object.data                  
          bm = bmesh.new()
          bm.from_mesh(mesh) 
  
          materials = bpy.data.materials      #get current meshs materials
  
          for index in range(len(materials)):         #get corresponding faces of material 
  
              for face in bm.faces:      
                  if face.material_index == index: #select face that matches current material
                      face.select = True
  
                      for L in face.loops:
                          L[bm.loops.layers.color.active] = materials[index].diffuse_color
  
         # bpy.data.materials = [] #remove all materials from material tab
  
          bm.to_mesh(mesh) #Assign new mesh from bmesh
          bm.free()
  </code></pre>
  
  <p>Thanks in advance.</p>