3
$\begingroup$

When i want to find the vertex within a mesh object that is closest to a given point in space, i can do something like this:

import bpy
p     = Vector((1,1,1))
ob    = bpy.context.object
me    = ob.data
verts = me.vertices
distances = [(v.co - p).length for v in verts]
val, idx = min((val, idx) for (idx, val) in enumerate(distances))

Then idx is the index of the closest vertex.

But is there is a ready made function available that gives back the index of the closest vertex ?

$\endgroup$
5
$\begingroup$

I don't think that there is a single function for that, but you can use the mathutils.kdtree module to query closest points.

If you sort the vertices of your mesh into a kd-tree you can just call

co, index, dist = my_kd_tree.find(p)

co will contain the coordinates of the closest point, index its index and dist the distance between p and the closest point. See the module documentation for the complete example.

If you want to query many closest points, using the kd-tree will be much faster than iterating over all vertices.

$\endgroup$
  • $\begingroup$ Is this similar to ICP? $\endgroup$ – June Wang Aug 29 at 15:21
  • $\begingroup$ Do you mean Iterative Closest Point registration? Then no, this will just give you the closest point to coordinate p and not register meshes. $\endgroup$ – maddin45 Aug 30 at 6:57
  • $\begingroup$ Thanks. I don't think there's a tool in blender to do dense correspondence between models, or is there? $\endgroup$ – June Wang Aug 30 at 16:07
  • $\begingroup$ Not out of the box, as far as I know. There is a (paid) addon for ICP, though: blendermarket.com/products/… $\endgroup$ – maddin45 Sep 2 at 10:20

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.