gpt4 book ai didi

python - 将 python 代码向量化为 numpy

转载 作者:行者123 更新时间:2023-11-28 21:38:36 25 4
gpt4 key购买 nike

我有以下代码片段(用于霍夫圆变换):

for r in range(1, 11):
for t in range(0, 360):
trad = np.deg2rad(t)

b = x - r * np.cos(trad)
a = y - r * np.sin(trad)

b = np.floor(b).astype('int')
a = np.floor(a).astype('int')

A[a, b, r-1] += 1

其中 A 是形状为 (height, width, 10) 的 3D 数组,并且heightwidth 表示给定图像的大小。我的目标是将代码段专门转换为 numpy 代码。

我的尝试是这样的:

arr_r = np.arange(1, 11)
arr_t = np.deg2rad(np.arange(0, 360))

arr_cos_t = np.cos(arr_t)
arr_sin_t = np.sin(arr_t)

arr_rcos = arr_r[..., np.newaxis] * arr_cos_t[np.newaxis, ...]
arr_rsin = arr_r[..., np.newaxis] * arr_sin_t[np.newaxis, ...]

arr_a = (y - arr_rsin).flatten().astype('int')
arr_b = (x - arr_rcos).flatten().astype('int')

其中 xy 是两个标量值。

我在转换增量部分时遇到问题:A[a,b,r] += 1。我想到了这个:A[a,b,r] 计算对 (a,b,r) 出现的次数,所以一个线索是使用笛卡尔积(但数组太大)。

我可以使用任何提示或技巧吗?

非常感谢!

编辑:填充A后,我需要(a,b,r)作为argmax(A)。元组 (a,b,r) 标识一个圆,它在 A 中的值表示置信度值。所以我想要 A 中具有最高值的那个元组。这是霍夫圆变换的投票算法的一部分:find circle parameter with unknown radius .

最佳答案

方法#1

这是利用 broadcasting 的一种方式获取计数并更新 A(假设在中间步骤中计算的 ab 值为正值)-

d0,d1,d2 = A.shape    
arr_r = np.arange(1, 11)
arr_t = np.deg2rad(np.arange(0, 360))

arr_b = np.floor(x - arr_r[:,None] * np.cos(arr_t)).astype('int')
arr_a = np.floor(y - arr_r[:,None] * np.sin(arr_t)).astype('int')

idx = (arr_a*d1*d2) + (arr_b * d2) + (arr_r-1)[:,None]

A.flat[:idx.max()+1] += np.bincount(idx.ravel())
# OR A.flat += np.bincount(idx.ravel(), minlength=A.size)

方法#2

或者,我们可以避免 bincount 来替换 approach #1 中的最后一步,就像这样 -

idx.ravel().sort()
idx.shape = (-1)
grp_idx = np.flatnonzero(np.concatenate(([True], idx[1:]!=idx[:-1],[True])))
A.flat[idx[grp_idx[:-1]]] += np.diff(grp_idx)

使用 numexpr 进行改进

我们还可以利用 numexpr module用于更快的正弦、余弦计算,就像这样 -

import numexpr as ne

arr_r2D = arr_r[:,None]
arr_b = ne.evaluate('floor(x - arr_r2D * cos(arr_t))').astype(int)
arr_a = ne.evaluate('floor(y - arr_r2D * sin(arr_t))').astype(int)

关于python - 将 python 代码向量化为 numpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48013431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com