gpt4 book ai didi

python - python 3 的 weave 替代品

转载 作者:行者123 更新时间:2023-12-01 09:24:19 38 4
gpt4 key购买 nike

我有一个来自 here 的函数它使用weave。我是否可以在 Python 3 中运行此代码而无需重写?

代码:

def _thinningIteration(im, iter):
I, M = im, np.zeros(im.shape, np.uint8)
expr = """
for (int i = 1; i < NI[0]-1; i++) {
for (int j = 1; j < NI[1]-1; j++) {
int p2 = I2(i-1, j);
int p3 = I2(i-1, j+1);
int p4 = I2(i, j+1);
int p5 = I2(i+1, j+1);
int p6 = I2(i+1, j);
int p7 = I2(i+1, j-1);
int p8 = I2(i, j-1);
int p9 = I2(i-1, j-1);
int A = (p2 == 0 && p3 == 1) + (p3 == 0 && p4 == 1) +
(p4 == 0 && p5 == 1) + (p5 == 0 && p6 == 1) +
(p6 == 0 && p7 == 1) + (p7 == 0 && p8 == 1) +
(p8 == 0 && p9 == 1) + (p9 == 0 && p2 == 1);
int B = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9;
int m1 = iter == 0 ? (p2 * p4 * p6) : (p2 * p4 * p8);
int m2 = iter == 0 ? (p4 * p6 * p8) : (p2 * p6 * p8);
if (A == 1 && B >= 2 && B <= 6 && m1 == 0 && m2 == 0) {
M2(i,j) = 1;
}
}
}
"""

weave.inline(expr, ["I", "iter", "M"])
return (I & ~M)

最佳答案

Numba可以作为替代解决方案。它即时编译Python代码,并且用法非常简洁。

上面的代码可以用Python用装饰器重写:

from numba import jit

@jit
def _thinningIteration(im, iter_):
M = np.zeros(im.shape, np.uint8)
h, w = im.shape
for i in range(1, h - 1):
for j in range(1, w - 1):
p2 = im[i - 1, j]
p3 = im[i - 1, j + 1]
p4 = im[i, j + 1]
p5 = im[i + 1, j + 1]
p6 = im[i + 1, j]
p7 = im[i + 1, j - 1]
p8 = im[i, j - 1]
p9 = im[i - 1, j - 1]
A = (p2 == 0 and p3 == 1) + (p3 == 0 and p4 == 1) + \
(p4 == 0 and p5 == 1) + (p5 == 0 and p6 == 1) + \
(p6 == 0 and p7 == 1) + (p7 == 0 and p8 == 1) + \
(p8 == 0 and p9 == 1) + (p9 == 0 and p2 == 1)
B = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9
m1 = (p2 * p4 * p6) if (iter_ == 0) else (p2 * p4 * p8)
m2 = (p4 * p6 * p8) if (iter_ == 0) else (p2 * p6 * p8)
if A == 1 and B >= 2 and B <=6 and m1 == 0 and m2 == 0:
M[i, j] = 1

return im & ~M

它可以在Python-2.x和Python-3.x中执行,性能接近C。查看this了解更多详情。

关于python - python 3 的 weave 替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50560404/

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