Let P be the matrix of pixel data. Its shape is (N,3), where N is the total number of pixels (height * width), and the columns represent the R, G, B channels. So, P=p1p, where each pi=[pi1,p is a 1x3 row vector for the i-th pixel.
Let C be the matrix of palette colors. Its shape is (M,3), where M is the number of colors in the palette, and the columns represent the R, G, B channels. So, , where each is a 1x3 row vector for the -th color.
pixels[:, np.newaxis]:
This operation takes the N x 3 matrix P and inserts a new axis, effectively reshaping it into a N x 1 x 3 tensor. Conceptually, this prepares for element-wise subtraction with broadcasting.
Let's call this reshaped version P′. It's a tensor where P.
pixels[:, np.newaxis] - palette:
This is the core subtraction using NumPy broadcasting. We are subtracting the M x 3 matrix C from the N x 1 x 3 tensor P′.
NumPy broadcasts P′ from (N, 1, 3) to (N, M, 3) and from to .
(...) ** 2:
This is element-wise squaring of the Δ tensor. The shape remains (N, M, 3).
Let's call this result Δ2. The element Δ.
np.sum(..., axis=2):
This sums the elements of Δ2 along the last axis (axis 2, the color channel dimension).
The result is a matrix, let's call it S, with shape (N, M). Each element Si,j is the sum of squared differences for all color channels between pixel and color :
np.sqrt(...):
This is element-wise square root of the matrix S.
The final result, distances, is a matrix D with shape (N, M). Each element Di,j is the Euclidean distance between the i-th pixel and the -th palette color:
In summary, the line of code computes a distance matrix D where the element Di,j is the Euclidean distance between the i-th pixel vector p (a row in ) and the -th color vector (a row in ).
This can be expressed concisely using vector norms:
Let pi∈R3 be the i-th row of P and be the -th row of .
The matrix is given by:
Di,j=∣∣pi−c
for i=1,…,N and j=1,…,M.
2
⋮
pN
i
2
,
pi3
]
C=c1c2⋮cM
cj=[cj1,cj2,cj3]
j
i,1,k
′
=
pik
C
(M, 3)
(1, M, 3)
The subtraction then happens element-wise on these broadcasted shapes.
The result is a tensor, let's call it Δ, with shape (N, M, 3). Each element Δi,j,k is the difference in the k-th color channel between the i-th pixel and the j-th palette color:
Δi,j,k=pik−c
This tensor Δ can be seen as a stack of N matrices, where the i-th matrix is (pi−c1;pi−c2;…;pi−cM)T, or as a stack of M matrices, where the j-th matrix has rows p1−cj,p2. The element Δi,j,k represents the difference (pi−cj)k.
i
,
j
,
k
2
=
(pik−
cjk)2
i
j
Si,j=∑k=13(pik−cjk)2
This is the squared Euclidean distance between the vectors pi and cj: Si,j=∣∣pi−cj∣∣22.