简体   繁体   中英

Sort colours list by Euclidean Distance

I am trying to sort my colours (which are in colour space CieLAB) by euclidean distance. So I am using the following code however it rearranges my colours instead of sorting. Do I need to specify a different axis or use a different function. If I need a different function can you suggest which one will work?

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

Result (notice how it has rearranged the colours?):

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

It should be:

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

I hope that I understood the question,
Maybe you should first calculate the pairwise distances, and then sort by these distances.

something like that:

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)

Will print

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

If I understood your question correctly you want to sort by Euclidean norm, right?

Something like

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

or using np.einsum (sort by a dot a row-wise)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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