如何使用python从特定像素中找到最近的x,y坐标

2024-04-19 09:34:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是找到每个像素最近的x,y点坐标。基于此,我必须给像素点上色。你知道吗

这是我尝试过的, 下面的代码将绘制这些点。你知道吗

import numpy as np
import matplotlib.pyplot as plt 

points = np.array([[0,40],[0,0],[5,30],[4,10],[10,25],[20,5],[30,35],[35,3],[50,0],[45,15],[40,22],[50,40]]) 
print (points)
x1, y1 = zip(*points)
plt.plot(x1,y1,'.')
plt.show()

Here is the output of the above code 现在找到每个像素的最近点。 我发现像这样的东西,我必须手动给每个像素坐标,以获得最近的点。你知道吗

from scipy import spatial
import numpy as np
A = np.random.random((10,2))*100
print (A)
pt = np.array([[6, 30],[9,80]])
print (pt)
for each in pt:
    A[spatial.KDTree(A).query(each)[1]] # <-- the nearest point 
    distance,index = spatial.KDTree(A).query(each)
    print (distance) # <-- The distances to the nearest neighbors
    print (index) # <-- The locations of the neighbors
    print  (A[index])

输出是这样的

[[1.76886192e+01 1.75054781e+01]
 [4.17533199e+01 9.94619127e+01]
 [5.30943347e+01 9.73358766e+01]
 [3.05607891e+00 8.14782701e+01]
 [5.88049334e+01 3.46475520e+01]
 [9.86076676e+01 8.98375851e+01]
 [9.54423012e+01 8.97209269e+01]
 [2.62715747e+01 3.81651805e-02]
 [6.59340306e+00 4.44893348e+01]
 [6.66997434e+01 3.62820929e+01]]
[[ 6 30]
 [ 9 80]]
14.50148095039858
8
[ 6.59340306 44.48933479]
6.124988197559344
3
[ 3.05607891 81.4782701 ]

我不想手动给出每个点,而是从图像中提取每个像素,然后找到最近的蓝点。这是我的第一个问题。你知道吗

然后我想把这些点分为两类, 基于像素和点我想给它上色,基本上我想在它上面做一个聚类。 Something like this  am looking for

这是不恰当的形式。但最后我还是要这样。 提前谢谢各位。你知道吗


Tags: theimportnumpyptindexasnpplt
2条回答

您可以使用scikit学习:

from sklearn.neighbors import KNeighborsClassifier
neigh = KNeighborsClassifier(n_neighbors=1)
labels = list(range(len(points)))
neigh.fit(points, labels) 
pred = neigh.predict(np.random.random((10,2))*50)

如果想要点本身而不是它们的类标签,可以这样做

points[pred]
  • 使用cKDTree而不是KDTree,后者更快(参见answer)。你知道吗
  • 您可以为kdtree提供一个要查询的点数组,而不是在所有点上循环。你知道吗
  • 与查询kdtree相比,构造kdtree是一项代价高昂的操作,因此一次构造kdtree,多次查询kdtree。你知道吗

比较以下两个代码段,在我的测试中,第二个代码段的运行速度快了800倍。你知道吗

from timeit import default_timer as timer

np.random.seed(0)
A = np.random.random((1000,2))*100
pt = np.random.randint(0,100,(100,2))

start1 = timer()
for each in pt:
    A[spatial.KDTree(A).query(each)[1]] 
    distance,index = spatial.KDTree(A).query(each)
end1 = timer()
print end1-start1

start2 = timer()
kdt = spatial.cKDTree(A)  # cKDTree + outside construction 
distance,index = kdt.query(pt)  
A[index] 
end2 = timer()
print end2-start2

相关问题 更多 >