猿问

python中的三边测量

我正在研究定位系统。我的输入是一个字典,它会给我们从点(x1,y1)等半径为 d1 的圆。我想要的输出是一个数组(类似于二维坐标系),其中相交区域标记为 1,其余为 0。我试过这个:


xsize=3000

ysize=2000

lis={(x1,y1):d1,(x2,y2):d2,(x3,y3):d3}

array=np.zeros((xsize,ysize))

for i in range(xsize-1):

    for j in range(ysize-1):

        for element in lis:

            if distance((i,j),element)<=(lis[element]):

                array[i][j]=1

            else:

                array[i][j]=0

                break

def distance(p1,p2):

    return math.sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2)

唯一的问题是数组很大并且花费的时间太长(循环数为 1000 万次),尤其是在树莓派上,否则会起作用。有没有办法使用openCV和图像来做,然后画圆圈来更快地获得相交区域?


它必须是 python 2.x。


江户川乱折腾
浏览 223回答 2
2回答

蛊毒传说

由于您已经在使用 numpy,请尝试以矢量化方式重写您的操作,而不是使用循环。# choose appropriate dtype for better perfdtype = np.float32# take all indices in an arrayindices = np.indices((ysize, xsize), dtype=dtype).Tpoints = np.array(list(lis.keys()), dtype=dtype)# squared distance from all indices to all pointsdist = (indices[..., np.newaxis] - points.T) ** 2dist = dist.sum(axis=-2)# squared circle radiidist_thresh = np.array(list(lis.values()), dtype=dtype) ** 2intersect = np.all(dist <= dist_thresh, axis=-1)在我的机器上,这比 for 循环版本快 60 倍左右。它仍然是一个蛮力版本,可能对所有坐标进行许多不必要的计算。问题中没有给出圆圈,因此很难对它们进行推理。如果它们覆盖的区域相对较小,那么如果考虑较小的区域,问题的解决速度会快得多(仍然是计算上的,而不是分析上的)。例如,代替测试所有坐标,可以使用圆的边界框的交点,这可以显着减少计算负载。
随时随地看视频慕课网APP

相关分类

Python
我要回答