Reputation: 113
Orginal
and Mutated
are images.
I need to get the difference of each r,g,b separately. I got this code to work, but it is to slow. Any help on making this fast would be nice! :)
Orginal = np.asarray(Orginal).copy()
Mutated = np.asarray(Mutated).copy()
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
Upvotes: 1
Views: 144
Reputation: 221714
Here's one approach to do all those in one summation with ndarray.sum
-
DeltaRed, DeltaGreen, DeltaBlue = Orginal.sum((0,1)) - Mutated.sum((0,1))
Here's another with np.einsum
and hopefully faster one, when working with uint8
images -
org_diff = np.einsum('ijk->k',Orginal.astype('uint64'))
mut_diff = np.einsum('ijk->k',Mutated.astype('uint64'))
DeltaRed, DeltaGreen, DeltaBlue = org_diff - mut_diff
Upvotes: 1
Reputation: 113
This was the code from beginning that worked.
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
Upvotes: 0
Reputation: 18446
It should be a whole lot faster if you didn't go the extra mile of zipping and then summing up each dimension instead of using numpy's sum function:
DeltaRed = np.sum(OR) - np.sum(MR)
DeltaGreen = np.sum(OG) - np.sum(MG)
DeltaBlue = np.sum(OB) - np.sum(MB)
Upvotes: 3