Skip to content

Instantly share code, notes, and snippets.

@tamask
Created December 27, 2011 17:28
Show Gist options
  • Save tamask/1524468 to your computer and use it in GitHub Desktop.
Save tamask/1524468 to your computer and use it in GitHub Desktop.
Bake Vertex Colors
import bpy
bl_info = {
'name': 'Bake Vertex Colors',
'author': 'Tamas Kemenczy',
'version': (0, 1),
'blender': (2, 6, 1),
'location': 'View3D > Specials > Bake Vertex Colors',
'description': 'Bake the active uv texture image to vertex colors',
'category': 'Mesh'
}
def bake_vertex_colors(obj):
uv_texture = obj.data.uv_textures.active
colors = obj.data.vertex_colors.new(uv_texture.name)
pixels = list(uv_texture.data[0].image.pixels)
for face_index, face_uv in enumerate(uv_texture.data):
image_width, image_height = face_uv.image.size
face_color = colors.data[face_index]
uv_coords = (face_uv.uv1, face_uv.uv2, face_uv.uv3, face_uv.uv4)
if (len(face_uv.uv) == 3):
uv_coords = uv_coords[:3]
for uv_index, uv_coord in enumerate(uv_coords):
x = int(uv_coord.x * image_width) % image_width
y = int(uv_coord.y * image_height) % image_height
offset = (y * image_width + x) * 4
r = pixels[offset + 0]
g = pixels[offset + 1]
b = pixels[offset + 2]
setattr(colors.data[face_index], 'color%i' % (uv_index + 1), (r, g, b))
face_uv.image = None
class BakeVertexColors(bpy.types.Operator):
bl_idname = 'mesh.bake_vertex_colors'
bl_label = 'Bake Vertex Colors'
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
obj = context.active_object
return (obj and obj.type == 'MESH')
def execute(self, context):
bake_vertex_colors(context.active_object)
return {'FINISHED'}
def menu_func(self, context):
self.layout.operator(BakeVertexColors.bl_idname, text='Bake Vertex Colors')
def register():
bpy.utils.register_module(__name__)
bpy.types.VIEW3D_MT_object_specials.append(menu_func)
def unregister():
bpy.utils.unregister_module(__name__)
bpy.types.VIEW3D_MT_object_specials.remove(menu_func)
if __name__ == "__main__":
register()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment