繁体   English   中英

按欧几里得距离对颜色列表进行排序

[英]Sort colours list by Euclidean Distance

我试图按欧几里得距离对我的颜色(在CieLAB颜色空间中)排序。 所以我正在使用以下代码,但是它重新排列了我的颜色,而不是进行排序。 我是否需要指定其他轴或使用其他功能。 如果我需要其他功能,您可以建议哪个功能起作用?

a = np.array([(255,9,255), (0,0,0), (125,125,4)])
a.sort(axis=0)
print(a)

结果(注意它是如何重新排列颜色的?):

[[  0   0   0]
 [  4 125 125]
 [  9 255 255]]

它应该是:

[[  0   0   0]
 [  125 125 4]
 [  255 9 255]]

我希望我理解了这个问题,
也许您应该首先计算成对的距离,然后按这些距离排序。

像这样的东西:

import numpy as np
from scipy.spatial.distance import cdist


def sort_by_eucledian_distance(a):
    dist = cdist(a, a)[:, 0] # calculate distances
    dist = sorted(zip(dist, np.arange(len(dist)))) #add indexes and sort
    idxs = [v[1] for v in dist] # get the new, sorted indexes
    return a[idxs]

a = np.array([(255,9,255), (0,0,0), (125,125,4)])
b = sort_by_eucledian_distance(a)
print(b)

将打印

array([[  0.,   0.,   0.],          
       [125.,   9.,   4.],          
       [255., 125., 255.]])  

如果我正确理解了您的问题,您想按欧几里得范数排序,对吗?

就像是

a[np.linalg.norm(a, axis=1).argsort()]

或使用np.einsum (按a dot a行排序)

a[np.einsum("ij,ij->i", a, a).argsort()]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM