Python - 如何根据 3D(r,g,b)空间中源颜色的颜色 "distance"对颜色列表进行排序?

标签 python list sorting tuples

以下是我用 Python 编写的应用程序的基本步骤:

  1. 生成随机颜色列表
  2. 为这些颜色中的每一种创建一个映射,根据该颜色与 3D (r, g, b) 空间中“源颜色”的距离进行索引。 (例如,橙色 (255, 150, 0) 比深蓝色 (0, 0, 100) 更接近红色 (255, 0, 0)。现在,我有一个格式为 (distance, color ).
  3. 根据我计算的距离(从最低到最高)对该元组列表进行排序。
  4. 检索已排序颜色的列表

这是我的函数,我收到以下错误:TypeError: 'int' object has no attribute '_getitem_' on the line sorted_by_dist =排序(colorMap,key=lambda tup:tup[0])

# Sorts a list of colors according to distance from the source color
def sort_colors(colors, source):
    colorMap = ()
    sortedColors = list()
    for i in range(len(colors)):
        dist = dist_3d(colors[i], source)
        colorMap = colorMap + (dist, colors[i])

    sorted_by_dist = sorted(colorMap, key=lambda tup: tup[0])

    for (d, c) in sorted_by_dist:
        sortedColors.append(c)

    return sortedColors

假设我的 dist_3d() 函数是正确的并返回一个整数值(确实如此),我做错了什么?我不明白。

最佳答案

您将 colorMap 构建为一个大的单维元组,第一个索引是 int。因此,您的 lambda 被传递给一个 int,然后您尝试对其进行索引。

你可能想要一个元组列表:

colorMap = []
...
    dist = dist_3d(colors[i], source)
    colorMap.append((dist, colors[i]))

在排序颜色的方法方面,我实际上使用了 kdtree module为此,加载了我所有的 RGB 元组。然后我可以向它请求 N 个最接近给定颜色元组的颜色:

from kdtree import KDTree

colors = [(10,10,10),(250,50,5),(100,50,20)]
query_color = (175, 25, 50)

tree = KDTree.construct_from_data(data)
# query the 2 closest colors
nearest = tree.query(query_point=query_color, t=2)

关于Python - 如何根据 3D(r,g,b)空间中源颜色的颜色 "distance"对颜色列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14168456/

相关文章:

Python 使用自定义键对 2D 列表进行排序

python - 在python的父文件夹中导入自定义模块

python - 将数字和字符串列表转换为单个字符串 python

c# - 当列表索引超出范围时,Linq 获取第一个或最后一个元素

arrays - 为什么需要Array类的'<'重载?

javascript - 如何在javascript中按相关性对搜索结果进行排序

c# - 我如何在 python 中反序列化 C# datetime?

python - 值错误 : Invalid reduction dimension 1 for input with 1 dimensions

python - 为什么 list() == 1 给出结果而 list() > 1 是错误的?

image - 如何使用 Flutter 将 BASE64 字符串转换为 Image?