使用 numpy 逐像素矢量化 2 个窗口图像集之间的误差计算

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

我正在尝试逐个像素地计算 2 windowed 图像集(每个图像)之间的误差。为此,我将编码化 img 的值减去原始 img。 这样做之后,我想计算每个像素到 0 的距离(使用 RGB 图像的 3 个维度)。我现在正在搜索的结果是一个与原始数据形状相同但只有一维 (l2_matrix) 的新矩阵。

我为此使用的代码是:

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)

如您所见,我有一个 5 维矩阵,其形状为:([=19= 的数量],每个 window 中的图像数量,x 轴,y 轴,维数).上面的代码工作正常,但我想改进 it.I 已尝试对其进行矢量化,但我不知道如何正确执行(我已经阅读了一些帖子,其中包含如何执行此操作的示例,但它是为了更简单的目的,我无法将其推断为这个问题)。

您可以使用 np.linalg.norm 定义要计算范数的轴。

比如这里第1张图片的第一个三通道像素的范数window:

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

因此您可以将 l2_matrix 定义为:

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

作为n_windows_max, n_imgs_window_max, x_max, y_max的一个维度。

如果你最后需要额外的维度,你可以这样做:

l2_matrix.reshape(*l2_matrix.shape, 1)