Javier C
Javier C

Reputation: 95

Vectorize the calculous of the error between 2 windowed sets of images pixel by pixel using numpy

I'm trying to calculate the error between 2 windowed sets of images pixel by pixel (of each image). To do that I'm subtracting the value of the codified img to the original img. After doing that I want to calculate the distance of each pixel to 0 (using the 3 dimensions of the RGB image). The result that I'm searching right now is a new matrix with the same shape as the original data but with only 1 dimension (l2_matrix). 

The code that I'm using for this is:

n_windows_max, n_imgs_window_max, x_max, y_max, n_dim = diff_matrix.shape

l2_matrix = np.zeros((n_windows_max,n_imgs_window_max,x_max, y_max, 1))

n_window = 0
n_img_window = 0
x_i = 0
y_i = 0

for n_window in range(n_windows_max): # read each window
  for n_img_window in range(n_imgs_window_max): #read all the images of each window
    for x_i in range(x_max): 
      for y_i in range(y_max): 
        a0 = diff_matrix[n_window, n_img_window, x_i, y_i, 0]
        a1 = diff_matrix[n_window, n_img_window, x_i, y_i, 1]
        a2 = diff_matrix[n_window, n_img_window, x_i, y_i, 2]

        a = array([a0, a1, a2])
        l2_matrix[n_window, n_img_window, x_i, y_i, 0] = norm(a)

As you can see I have a 5 dimensional matrix where the shape is:(number of windows, number of images in each window, x axis, y axis, number of the dimension). The code above works fine, but I want to improve it.I have tried to vectorize it, but I don't know how to do it properly (I have read some posts with examples of how to do it but it was for easier purposes and I wasn't able to extrapolate it to this problem).

Upvotes: 1

Views: 35

Answers (1)

Ivan
Ivan

Reputation: 40648

You can define the axis you want to calculate the norm on with np.linalg.norm.

For example, here the norm of the first three-channel pixel of the 1st image of 1st window:

np.linalg.norm(diff_matrix[:1, :1, :1, :1], axis=4)

So you can just define l2_matrix as:

l2_matrix = np.linalg.norm(diff_matrix, axis=4)

Which as a dimension of n_windows_max, n_imgs_window_max, x_max, y_max.

And if you need that extra dimension at the end you can do:

l2_matrix.reshape(*l2_matrix.shape, 1)

Upvotes: 1

Related Questions