This is a loop for extracting the RGB values of two images, and calculating the sum of squared differences across all three channels. Running this code directly in my main.py takes 0.07 sec. The speed gets reduced to 1sec if I run it in this .pyx file instead. I have read about cdef the functions, but I have had no success of passing the arrays then. Any help on converting this function to cdef function would be appreciated. I really need this loop to go as fast as possible.
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
My Main.py function call
NewScore = cythona.fittnes(numpy.array(Orginal), numpy.array(MutatedImage))
Got me interested to know about the speedup numbers, so I am posting this as a solution. So, as stated/discussed in the comments, if the inputs are NumPy arrays, you could use native NumPy tools, and in this case
ndarray.sum()
, like so -You can also use the very efficient
np.einsum
for the same task, like so -Runtime tests
Define functions -
Timings -