有效计算平方差和

2024-09-27 07:32:34 发布

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

这是一个循环,用于提取两个图像的RGB值,并计算所有三个通道的平方差之和。 直接在我的主.py需要0.07秒。如果我在这个.pyx文件中运行它,速度会降低到1秒。我读过关于cdef函数的文章,但是我没有成功地传递数组。如能帮助您将此函数转换为cdef函数,我们将不胜感激。我真的需要这个循环尽快进行。在

from cpython cimport array
import array
import numpy as np
cimport numpy as np

def fittnes(Orginal, Mutated):

    Fittnes = 0

    for x in range(0, 299):

        for y in range(0, 299):

            DeltaRed   = (Orginal[x][y][0] - Mutated[x][y][0])
            DeltaGreen = (Orginal[x][y][1] - Mutated[x][y][1])
            DeltaBlue  = (Orginal[x][y][2] - Mutated[x][y][2])

            Fittnes += (DeltaRed * DeltaRed + DeltaGreen * DeltaGreen + DeltaBlue * DeltaBlue)

    return Fittnes

我的主.py函数调用

^{pr2}$

Tags: 函数pyimportnumpyasnparraycdef
1条回答
网友
1楼 · 发布于 2024-09-27 07:32:34

让我有兴趣知道加速数字,所以我把这个作为一个解决方案。因此,正如注释中所述/讨论的,如果输入是NumPy数组,那么可以使用本机NumPy工具,在本例中是^{},如下-

out = ((Orginal - Mutated)**2).sum()

您还可以将非常高效的^{}用于相同的任务,如-

^{pr2}$

运行时测试

定义函数-

def org_app(Orginal,Mutated):
    Fittnes = 0
    for x in range(0, Orginal.shape[0]):
        for y in range(0, Orginal.shape[1]):
            DR = (Orginal[x][y][0] - Mutated[x][y][0])
            DG = (Orginal[x][y][1] - Mutated[x][y][1])
            DB  = (Orginal[x][y][2] - Mutated[x][y][2])
            Fittnes += (DR * DR + DG * DG + DB * DB)
    return Fittnes

def einsum_based(Orginal,Mutated):
    sub = Orginal - Mutated
    return np.einsum('ijk,ijk->',sub,sub)

def dot_based(Orginal,Mutated): # @ali_m's suggestion
    sub = Orginal - Mutated
    return np.dot(sub.ravel(), sub.ravel())

def vdot_based(Orginal,Mutated):  # variant of @ali_m's suggestion
    sub = Orginal - Mutated
    return np.vdot(sub, sub)

时间安排-

In [14]: M,N = 100,100
    ...: Orginal = np.random.rand(M,N,3)
    ...: Mutated = np.random.rand(M,N,3)
    ...: 

In [15]: %timeit org_app(Orginal,Mutated)
    ...: %timeit ((Orginal - Mutated)**2).sum()
    ...: %timeit einsum_based(Orginal,Mutated)
    ...: %timeit dot_based(Orginal,Mutated)
    ...: %timeit vdot_based(Orginal,Mutated)
    ...: 
10 loops, best of 3: 54.9 ms per loop
10000 loops, best of 3: 112 µs per loop
10000 loops, best of 3: 69.8 µs per loop
10000 loops, best of 3: 86.2 µs per loop
10000 loops, best of 3: 85.3 µs per loop

In [16]: # Inputs
    ...: M,N = 1000,1000
    ...: Orginal = np.random.rand(M,N,3)
    ...: Mutated = np.random.rand(M,N,3)
    ...: 

In [17]: %timeit org_app(Orginal,Mutated)
    ...: %timeit ((Orginal - Mutated)**2).sum()
    ...: %timeit einsum_based(Orginal,Mutated)
    ...: %timeit dot_based(Orginal,Mutated)
    ...: %timeit vdot_based(Orginal,Mutated)
    ...: 
1 loops, best of 3: 5.49 s per loop
10 loops, best of 3: 63 ms per loop
10 loops, best of 3: 23.9 ms per loop
10 loops, best of 3: 24.9 ms per loop
10 loops, best of 3: 24.9 ms per loop

相关问题 更多 >

    热门问题