如何按位置值对颜色的numpy数组排序? 我尝试过的但不起作用

我有一个可用颜色的数组,我说它们在YCrCb空间中,我想按Y通道(第一个通道)对数组进行排序,而不会弄乱颜色元素。

我的数组:

colors = np.array([[[191,142,109],[196,138,116],[193,144,111],[198,140,118]]],dtype=np.uint8)

colors.shape
# (1,4,3)

我想要的输出:

array([[[191,dtype=uint8)

我尝试过的但不起作用

我正在使用np.sort。但是我注意到如果我这样做:

np.sort(colors,axis=2)
# array([[[109,191],#         [116,196],#         [111,193],#         [118,198]]],dtype=uint8)

它不会重新排列元素,而是重新排列通道中元素的值。

我使用的另一种策略:

np.sort(pallete.reshape(-1,3),axis=0)
# array([[191,#        [193,#        [196,#        [198,118]],dtype=uint8)

那个误导了我,与我想要的东西非常相似,但是却弄乱了颜色元素。


lxlovekobe8 回答:如何按位置值对颜色的numpy数组排序? 我尝试过的但不起作用

colors = np.array([[[191,142,109],[196,138,116],[193,144,111],[198,140,118]]],dtype=np.uint8)
desired_output = np.array([[[191,dtype=np.uint8)
print(colors.shape)
# (1,4,3)

我的解决方案:

# get first column to collect only these value for easy sorting 
first_column = colors[:,:,0]
print(first_column)
# [[[191]
#  [196]
#  [193]
#  [198]]]

# argsort method return with indices of the sorted elements of the first column
# argsort with 'mergesort' a stable sort that mean doesn't mess the column elements as expected
# axis=None mean the flattening of result,make a simple vector
indices = first_column.argsort(kind='mergesort',axis=None)
print(indices)
# [0 2 1 3] # it will be the first element by indices[0]==0 what 0 point to 191 in first column vector
#           # it will be the second element by indices[1]==2 what 2 point to 193 in first column vector and so on

# make indeed the colors arrays in sort by indices
my_output = colors[:,indices]
# check equality of your desired output and my output 
print(np.array_equal(desired_output,my_output))
# True

# the aboves' short form
print(colors[:,colors[:,0].argsort(kind='mergesort',axis=None)])
# [[[191 142 109]
#  [193 144 111]
#  [196 138 116]
#  [198 140 118]]]

如果要按列0、1、2排序,请查看以下链接: Sorting arrays in NumPy by column

本文链接:https://www.f2er.com/3142287.html

大家都在问