I am trying to find the right scaling, angle and translation to align two images with different resolution, using differential_evolution (shown in the Code below), which works, but the more pixel I want to compare, the longer the runtime of my Code is.
My approach is the following in detail: I am using an affine transformation with the parameters sc1,sc2 (scaling factors),al(angle),u1 (horizonal translation) and u2 (vertical translation) on the coordinates of the higher resoluted images (coora2). I now want to find the minimum of the Sum of Squared Differences. The Code below is a simplified version of my real Data.
The approach works for small values for w1, h1 and w2,h2. My problem is, that the more data I have (increase w1, h1 or w2, h2) the runtime gets very, very long. For my original data I have w1=338, h1=514 and w2=3610 and h2 =5190 and the program is running for days now. I would be really thankful to get any kind of advice to speed up the Code to find my right parameters. The simplified code is the following:
from math import floor
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize
from scipy.optimize import Bounds
from scipy.optimize import differential_evolution
w1=8 #A1
h1=5
w2=25 #A2
h2=14
hw1=w1*h1
hw2=w2*h2
A1=np.ones((h1,w1))
A2=np.ones((h2,w2))
for n1 in np.arange(2,4):
A1[1][n1]=1000
for n2 in np.arange(5,9):
A2[6][n2]=1000
A2[7][n2]=1000
#Norm the raw data
maxA1=np.max(A1)
A1=1/maxA1*A1
#Norm the raw data
maxA2=np.max(A2)
A2=1/maxA2*A2
fig, axes = plt.subplots(1, 2)
axes[0].imshow(A2)
axes[0].set_title('original-A2')
axes[1].imshow(A1)
axes[1].set_title('shifted-A1')
plt.show()
def xy_to_pixelvalue(x,y,dataArray): #getting the values to the normed pixels
height=dataArray.shape[0]
width=dataArray.shape[1]
xcoord=floor((x+1)/2*(width-1))
ycoord=floor((y+1)/2*(height-1))
if -1 <=x<=1 and -1<=y<=1:
return dataArray[ycoord][xcoord]
else:
return(0)
#norming pixel coordinates
A1x=np.linspace(-1,1,w1)
A1y=np.linspace(-1,1,h1)
A2x=np.linspace(-1,1,w2)
A2y=np.linspace(-1,1,h2)
#normed coordinates of A2 in a matrix
Ap2=np.zeros((h2,w2,2))
for i in np.arange(0,h2):
for j in np.arange(0,w2):
Ap2[i][j]=(A2x[j],A2y[i])
#defining a vector with the coordinates of A2
d=[]
cdata=Ap2[:,:,0:2]
for i in np.arange(0,h2):
for j in np.arange(0,w2):
d.append((cdata[i][j][0],cdata[i][j][1]))
d=np.asarray(d)
coora2=d.transpose()
coora2=np.array(coora2, dtype=np.float64)
def tempsum3(x):
tempsum=0
for l in np.arange(0,hw2):
tempsum += (xy_to_pixelvalue(np.cos(np.radians(x[2]))*x[0]*coora2[0][l]-np.sin(np.radians(x[2]))*x[1]*coora2[1][l]+x[3],np.sin(np.radians(x[2]))*x[0]*coora2[0][l]+np.cos(np.radians(x[2]))*x[1]*coora2[1][l]+x[4],A1)-xy_to_pixelvalue(coora2[0][l],coora2[1][l],A2))**2
return tempsum
x0 = np.array([1,1,-0.5,0,0])
bounds = Bounds([0.1,0.1,-1,-4,-4], [5,5,2,4,4])
rslt = differential_evolution(tempsum3, bounds=bounds, popsize= 5*15, x0=x0)
print(rslt)