首页 > 解决方案 > 按欧几里得距离排序颜色列表

问题描述

我正在尝试按欧几里得距离对我的颜色(在颜色空间 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]]

标签: pythonnumpy

解决方案


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

类似的东西:

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.]])  

推荐阅读