# Nearest neighbour(closest point) search using vtkKdTree

**URL:** https://discourse.vtk.org/t/nearest-neighbour-closest-point-search-using-vtkkdtree/11250
**Category:** Support
**Tags:** python
**Created:** [April 19, 2023, 5:53am UTC](https://discourse.vtk.org/t/nearest-neighbour-closest-point-search-using-vtkkdtree/11250 "2023-04-19T05:53:02Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![liuzhongshu](https://discourse.vtk.org/user_avatar/discourse.vtk.org/liuzhongshu/32/6921_2.png) [@liuzhongshu](https://discourse.vtk.org/u/liuzhongshu)
#### Post date: [April 19, 2023, 5:53am UTC](https://discourse.vtk.org/t/nearest-neighbour-closest-point-search-using-vtkkdtree/11250/1 "2023-04-19T05:53:02Z")

</div>

I am using vtk’s kdtree to search closest point, here is a simple example that, to my surprise, returned a value that was not what I was expecting

```auto
import vtk

points = vtk.vtkPoints()
points.InsertNextPoint(1, 0, 0)
points.InsertNextPoint(0, 1, 0)
points.InsertNextPoint(0, 0, 1)

kdtree = vtk.vtkKdTree()
kdtree.BuildLocatorFromPoints(points)

dist=vtk.reference(0.0)
p = kdtree.FindClosestPoint(0,0,10,dist)

print(p,dist)

```

The printed result is `0 4.0` and the value I expect is `2 81`  
Did I make a mistake?

---

<div class="post-metadata">

### Author: ![Jens\_Munk\_Hansen](https://discourse.vtk.org/user_avatar/discourse.vtk.org/jens_munk_hansen/32/1215_2.png) [@Jens\_Munk\_Hansen](https://discourse.vtk.org/u/Jens_Munk_Hansen)
#### Post date: [April 19, 2023, 5:56pm UTC](https://discourse.vtk.org/t/nearest-neighbour-closest-point-search-using-vtkkdtree/11250/2 "2023-04-19T17:56:39Z")

</div>

At the top of my head this is a little puzzling for me. If you use the `vtkStaticPointLocator` which is also much faster, this approach works

```
import vtk

points = vtk.vtkPoints()
points.InsertNextPoint(1, 0, 0)
points.InsertNextPoint(0, 1, 0)
points.InsertNextPoint(0, 0, 1)

pd = vtk.vtkPolyData()
pd.SetPoints(points)

locator = vtk.vtkStaticPointLocator()
locator.SetDataSet(pd)

p = locator.FindClosestPoint(0,0,10)
print(pd.GetPoint(p))

```

Then you can compute distance afterwards. It could be due to the `vtkKdtree` needs cells to properly build

---

<div class="post-metadata">

### Author: ![liuzhongshu](https://discourse.vtk.org/user_avatar/discourse.vtk.org/liuzhongshu/32/6921_2.png) [@liuzhongshu](https://discourse.vtk.org/u/liuzhongshu)
#### Post date: [April 20, 2023, 2:51am UTC](https://discourse.vtk.org/t/nearest-neighbour-closest-point-search-using-vtkkdtree/11250/3 "2023-04-20T02:51:14Z")

</div>

Thanks, I tried both vtkStaticPointLocator and vtkPointLocator, they are both correct.
