无法理解此代码中的质心和距离公式

2024-04-27 13:29:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力理解8点算法的标准化过程。我指的是this code in MATLAB,由于没有matlab,我无法运行它。你知道吗

function Nmatrix = getNormMat2d(x)

Nmatrix - the normalization matrix
%       x - input data, dim: 3xN

% Get the centroid
centroid = mean(x, 2);
% Compute the distance to the centroid
dist = sqrt(sum((x - repmat(centroid, 1, size(x, 2))) .^ 2, 1));
% Get the mean distance
mean_dist = mean(dist);
% Craft normalization matrix
Nmatrix = [sqrt(2) / mean_dist, 0, -sqrt(2) / mean_dist * centroid(1);...
           0, sqrt(2) / mean_dist, -sqrt(2) / mean_dist * centroid(2);...
           0, 0, 1];

end

我试着用Python编写这个。但有几件事我不明白:

质心不应该是这样的吗

#dummy points 
x1 = np.array([20, 30, 40, 50, 60, 30, 20, 40])
y1 =  np.array([12, 34, 56, 78, 89, 45, 90, 29])
# did the following to give it the shape the matlab function expects
first=np.stack((x1,y1),axis = 1) 
ones=np.ones((8,1))
first = np.concatenate((first,ones),axis = 1)
p1 = np.ndarray.transpose(first)
#centroid
centroid_x = np.mean(p1[0,:])
centroid_y = np.mean(p1[1,:])

我不明白他们为什么用centroid = mean(x, 2);。除此之外,dist = sqrt(sum((x - repmat(centroid, 1, size(x, 2))) .^ 2, 1));这句话在我脑子里也不太清楚。你知道吗

请帮我理解这个

关于算法:

我们需要得到一个变换矩阵(平移和缩放),这样新的坐标系的原点就在质心上,平移之后坐标就被均匀缩放,这样原点到一个点的平均距离就等于$sqrt(2)$


Tags: the算法distnponesfunctionsqrtmean
1条回答
网友
1楼 · 发布于 2024-04-27 13:29:59

好吧,我们来看看这个

centroid = mean(x, 2);

取行的平均值,所以x是3行N列。这意味着centroid是3x1向量[xC ; yC ; zC]

dist = sqrt(sum((x - repmat(centroid, 1, size(x, 2))) .^ 2, 1));

让我们从外到内看一看

repmat(centroid, 1, size(x, 2))

centroid的N个副本生成矩阵。然后-取点和质心之间的差,得到一个3xN矩阵。.^2只是对3xN矩阵的每个元素进行平方运算。sum( ... , 1 )沿行添加(即,将x、y和z分量添加在一起)。然后sqrt取平方根。你知道吗

通过Matlab代码运行python示例

x1 = [20, 30, 40, 50, 60, 30, 20, 40];
y1 = [12, 34, 56, 78, 89, 45, 90, 29];
x = [ x1 ; y1 ];
centroid = mean(x, 2);
dist = sqrt(sum((x - repmat(centroid, 1, size(x, 2))) .^ 2, 1));
dist'

ans =

      45.1506159980127
      21.0731612483747
      4.19262745781211
      27.5513724703507
      42.1939346944558
      11.0602045641118
      39.3837291911266
      25.4033093316599

和相应的python

x1 = np.array([20, 30, 40, 50, 60, 30, 20, 40])
y1 =  np.array([12, 34, 56, 78, 89, 45, 90, 29])
x = np.column_stack((x1,y1))
centroid = np.mean( np.transpose( x ) )
dist = [ np.sqrt( np.sum( np.square( v - centroid ) ) ) for v in x ]
dist
[45.1506159980127, 21.073161248374674, 4.192627457812105, 27.551372470350728, 42.19393469445579, 11.060204564111823, 39.38372919112663, 25.40330933165992]

相关问题 更多 >