I've been searching high and low for a python script to select the highest or lowest vertex or vertices on the z axis in an object. I want to add these to a vertex group so I can use them in my code. Any help is appreciated.. thanks.
import bpy # get the object and its vertices obj = bpy.context.object # edit: now gets the currently active object # edit: to select vertices we have to be in OBJ mode first: bpy.ops.object.mode_set(mode="OBJECT") verts = obj.data.vertices # get the z-coordinates from each vertex and the maximum z_coords = [v.co for v in verts] max_z_coord = max(z_coords) # get list of all vertices that have the max. z-coordinate max_verts = [vertex for vertex in obj.data.vertices if vertex.co == max_z_coord]
To select vertices, one way is to change to OBJECT mode,
select the vertices, and change back to EDIT mode. (Another one would be to use
Notice that I've also changed two lines in the original answer above: We have to work on the active object (
obj = bpy.context.object) and we have to be in OBJECT mode (
The selection and switching to EDIT mode is done by appending these lines to the script:
# select the vertices: for v in verts: v.select = False for v in max_verts: v.select = True # set EDIT mode's select mode to "vertex select" bpy.context.tool_settings.mesh_select_mode = (True , False , False) # change to EDIT mode bpy.ops.object.mode_set(mode="EDIT")
Edit BMesh version
An edit mode script to select the maximum z value vertices.
Uses local space, edit to
space = 'GLOBAL' for global space.
Uses a tolerance of
TOL = 0.0000001 to check between values. Edit to suit. Set to zero for no tolerance
Sorted the vertices in z order. This is less efficient than finding the max. If though you also want the min the median, the top 10 etc, will come down to simple list slicing.
import bpy import bmesh from mathutils import Matrix space = 'LOCAL' # or 'GLOBAL' find = 'MAX' # or 'MIN' TOL = 1e-7 ob = bpy.context.object M = ob.matrix_world if space == 'GLOBAL' else Matrix() me = ob.data bm = bmesh.from_edit_mesh(me) verts = sorted(bm.verts, key=lambda v: (M @ v.co).z) bm.select_flush(False) #bm.select_flush_mode() z = (M @ verts[-1 if find == 'MAX' else 0].co).z for v in verts: v.select = abs((M @ v.co).z - z) < TOL bm.select_flush(True) bmesh.update_edit_mesh(me)
For example to add the top 3 verts to a vertex group
vg named "Group" Would need to do this in object mode
bm = bmesh.new() bm.from_mesh(me) verts = sorted(bm.verts, key=lambda v: (M @ v.co).z) vg = ob.vertex_groups.new(name="Top 3") vg.add([v.index for v in verts[:3], 1.0, 'REPLACE') vg = ob.vertex_groups.new(name="Lowest 3") vg.add([v.index for v in verts[-3:], 1.0, 'REPLACE')