I need to change vertex position in a shapekey through python. Is it possible to do?

Right now i can only get vertices coordinates. But how to change the vertex coordinate of shapekey?

import bpy

obj1 = bpy.context.selected_objects[0]
for vert in obj1.data.vertices:
    print(vert.co)  # this is a vertex coord of the mesh

For example i want to change avertex coordinates of a ShapeKey "Key1". http://i.imgur.com/erM03j9.png


Shape key coordinates live in a bmesh "layer"

I have included a copy of http://web.purplefrog.com/~thoth/blender/python-cookbook/explore-shape-keys.html here:

import bpy
import bmesh

def dump(mesh):

    bm = bmesh.new()

    for key in bm.verts.layers.shape.keys():
        val = bm.verts.layers.shape.get(key)
        print("%s = %s" % (key,val) )
        print("v=%f, f=%f" % ( sk.value, sk.frame))
        for i in range(len(bm.verts)):
            v = bm.verts[i]
            delta = v[val] - v.co
            if (delta.length > 0):
                print ( "v[%d]+%s" % ( i,delta) )


Code for creating and populating shape keys can be found at http://web.purplefrog.com/~thoth/blender/python-cookbook/shape-key-fin.html and I have extracted the most interesting bit here:

def addShapeKey(obj, i, nKeys, z1, z2, dTheta, thetaLag):
    kn = "phase %d"%i
    sk = obj.shape_key_add(kn)
    bm = bmesh.new()
    sl = bm.verts.layers.shape.get(kn)

    for u in range( math.floor(len(bm.verts) / 3)):
        t = math.pi*2*i/nKeys
        bm.verts[u*3][sl] = vert1For(u, t)
        bm.verts[u*3+1][sl] = vert2For(u, t, dTheta, z1)
        bm.verts[u*3+2][sl] = vert3For(u, t, dTheta, z2, thetaLag)

  • 3
    $\begingroup$ The Bmesh module is not required to access shape key data, the data path to the vertex coordinates in the standard API is Object.data.shape_keys.key_blocks['Key 1'].data[#].co (substitute Key 1 with the shape key name and # with the vertex index). $\endgroup$ – CodeManX Sep 5 '14 at 18:45

Thanks to all of you. CodeMax's line solved the issue! Just select some models with the same points count and make morphs.


import bpy

objAct = bpy.context.scene.objects.active
for obj in bpy.context.selected_objects:
    if obj != objAct:
        shapeKey = objAct.shape_key_add(from_mix=False)
        shapeKey.name = obj.name

        for vert in obj.data.vertices:
            shapeKey.data[vert.index].co = vert.co
            #print(vert.co)  # this is a vertex coord of the mesh

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.