T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 91 天:图片取色:KDTree 与最近颜色名

这是「Python 100 天」系列第 91 天的学习笔记:图片取色:KDTree 与最近颜色名。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

选一张图 → 统计出现最多的 15 种颜色 → 每种颜色给出最接近的 CSS 颜色名(比如 (135,206,235) → "SkyBlue")→ 显示在文本框里 → 可复制、可清空。

README 知识点:Tkinter、grid()、filedialog、RGB 转颜色名。

这是一个"看起来简单、技术上很漂亮"的小工具:核心是 KD 树最近邻搜索。

一、统计出现最多的颜色

1
2
3
4
5
6
7
def palette(img):
arr = np.asarray(img) # (H, W, 3)
palette, index = np.unique(asvoid(arr).ravel(), return_inverse=True)
palette = palette.view(arr.dtype).reshape(-1, arr.shape[-1])
count = np.bincount(index)
order = np.argsort(count)
return palette[order[::-1]]

逐步拆:

  1. np.asarray(img) → 三维数组(高、宽、3 通道);
  2. asvoid(arr).ravel() → 把每个像素的 3 个字节"打包"成一个 void 值,这样 np.unique 才能把 (135,206,235) 当成一个整体去重(否则它会分别去重 R、G、B 三个通道);
  3. np.unique(..., return_inverse=True) → 返回"去重后的颜色表" + "每个像素属于第几种颜色"的下标;
  4. palette.view(arr.dtype).reshape(-1, 3) → 把 void 再拆回 RGB 三元组;
  5. np.bincount(index) → 每种颜色出现多少次;
  6. np.argsort(count) 升序 → [::-1] 反转 → 按出现次数从多到少排序。

asvoid 的作用是"把结构化数据压成一维可比较的标量",这是 NumPy 里的高级技巧(Stack Overflow 上的经典答案)。

更简单的写法:PIL 自带 img.getcolors(maxcolors=256*256*256),或者 img.convert('P').getpalette()。但这份代码的思路(唯一化 + 计数 + 排序)值得理解。

二、RGB → 颜色名:KD 树

1
2
3
4
5
6
7
8
9
10
11
12
from scipy.spatial import KDTree
from webcolors import CSS3_HEX_TO_NAMES, hex_to_rgb

def convert_rgb_to_names(rgb_tuple):
names, rgb_values = [], []
for color_hex, color_name in CSS3_HEX_TO_NAMES.items():
names.append(color_name)
rgb_values.append(hex_to_rgb(color_hex))

kdt_db = KDTree(rgb_values)
distance, index = kdt_db.query(rgb_tuple)
return names[index].title()
  • CSS3_HEX_TO_NAMES 是 147 个 CSS3 标准颜色的字典("#87ceeb" → "skyblue");
  • 把每个 hex 转成 RGB 三元组,建一棵 KD 树(一种能快速找"最近点"的空间数据结构);
  • query(rgb) 返回距离最近的那个颜色的下标(和距离)。

暴力法要算 147 次距离;KD 树在颜色多时快得多。147 个点其实差别不大,但这是"最近邻搜索"的标准做法——图像检索、推荐系统里的向量相似度都是这套。

注意:它每次调用都重建一次 KD 树。这是明显的性能浪费——get_img_colors() 循环里对每个颜色都调一次 convert_rgb_to_names,等于重建 15 次树。应该把建树提到函数外(模块级只建一次)。

三、Text 控件与剪贴板

1
2
3
4
5
colors_text = Text(root, width=35, height=16, font=(TITLE_FONT, 14))
colors_text.insert(END, name + 'n')
colors_text.get("1.0", END) # 从第 1 行第 0 列到末尾
root.clipboard_append(text) # 写系统剪贴板
colors_text.delete("1.0", END) # 清空

Text 的索引是 "行.列" 字符串("1.0" = 第 1 行第 0 个字符),和 Entry 的整数索引完全不同。这是 Tkinter 最容易搞混的地方之一。

代码全文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# tkinter 全部名字。
from tkinter import *
# 文件对话框。
from tkinter import filedialog
# numpy:把图片变成数组做批量统计。
import numpy as np
# Pillow:读图并统一转成 RGB。
from PIL import Image
# KDTree:多维空间的最近邻搜索,这里用来找“最接近的颜色名”。
from scipy.spatial import KDTree
# webcolors 两个工具:CSS3_HEX_TO_NAMES 是 {'#f0f8ff': 'aliceblue', ...} 全表,
# hex_to_rgb 把 '#f0f8ff' 转成 (240, 248, 255)。
from webcolors import (
CSS3_HEX_TO_NAMES,
hex_to_rgb,
)

# 最多列出多少种颜色名。
NUMBER_OF_COLORS = 15
# 字体与配色。
TITLE_FONT = "Arial"
TITLE_COLOR = "#EFEFEF"
WORD_FONT = "Times New Roman"
WORD_COLOR = "#EEEEEE"
BACKGROUND_COLOR = "#222832"
BTN_BACKGROUND_COLOR = "#2F3847"


# 选图 → 统计主色 → 映射成颜色名 → 写进文本框。
def get_img_colors():
# 文件对话框。
img_file = filedialog.askopenfilename(
initialdir="/",
title="Select IMG",
# 过滤项写成 "*.jpg;*.jpeg;*.png" 这种分号串在部分平台不生效,
# 正确写法是模式元组:("*.jpg", "*.jpeg", "*.png")。
filetypes=(('Image Files', "*.jpg;*.jpeg;*.png"), ("All Files", "*.*"))
)
# Image.open(...).convert('RGB'):统一成三通道,避免 png 透明通道/gif 调色板干扰统计。
img = Image.open(img_file, 'r').convert('RGB')
# 调 palette() 拿按出现次数降序排列的颜色数组。
color_codes = palette(img)
# 收集去重后的颜色名。
color_names = []
# 逐色映射。
for code in color_codes:
# 两个条件:名字没出现过、且总数没超过上限 —— 避免重复与被近色刷屏。
if convert_rgb_to_names(code) not in color_names and len(color_names) < NUMBER_OF_COLORS:
color_names.append(convert_rgb_to_names(code))
# insert(END, ...):Text 控件追加一行;'n' 手动换行。
colors_text.insert(END, convert_rgb_to_names(code) + 'n')


# 统计调色板:返回按像素数从多到少排序的颜色列表。
def palette(img):
"""
Return palette in descending order of frequency
"""
# asarray:PIL 图 → numpy 数组,形状 (高, 宽, 3)。
arr = np.asarray(img)
# 关键技巧:把每个像素的 3 个字节打包成一个 void 标量,才能用 np.unique 去重计数。
# return_inverse=True 同时返回“每个像素属于第几个唯一色”的下标。
palette, index = np.unique(asvoid(arr).ravel(), return_inverse=True)
# 把打包后的标量“还原”成 (N, 3) 的 RGB 数组。
palette = palette.view(arr.dtype).reshape(-1, arr.shape[-1])
# bincount:统计每个下标的出现次数,即每种颜色的像素数。
count = np.bincount(index)
# argsort:按次数升序得到下标顺序。
order = np.argsort(count)
# [::-1] 反转成降序,再据此取颜色。
return palette[order[::-1]]


# 把 (H, W, 3) 的数组“按最后一个轴打包”成 (H, W) 的 void 数组。
# 参数 arr:任意形状的 ndarray;返回:每像素一个元素的数组。
def asvoid(arr):
"""View the array as dtype np.void (bytes)
This collapses ND-arrays to 1D-arrays, so you can perform 1D operations on them.
http://stackoverflow.com/a/16216866/190597 (Jaime)
http://stackoverflow.com/a/16840350/190597 (Jaime)
Warning:
>>> asvoid([-0.]) == asvoid([0.])
array([False], dtype=bool)
"""
# ascontiguousarray:保证内存连续,否则 view 会失败(跨步数组不能直接 view)。
arr = np.ascontiguousarray(arr)
# view + dtype((np.void, 3*itemsize)):每 3 个字节当作一个整体比较。
return arr.view(np.dtype((np.void, arr.dtype.itemsize * arr.shape[-1])))


# RGB → 最接近的 CSS3 颜色名。
def convert_rgb_to_names(rgb_tuple):
# A dictionary of all the hex and their respective names in css3
# 全量色表。
css3_db = CSS3_HEX_TO_NAMES
names = []
rgb_values = []
# 遍历色表:拆成名字列表与 RGB 列表(一一对应)。
for color_hex, color_name in css3_db.items():
names.append(color_name)
rgb_values.append(hex_to_rgb(color_hex))

# 建 KDTree:把所有候选色放进一棵树,之后每次查询是 O(log n)。
# 注意这行在函数内部,每处理一个颜色就重建一次树 —— 效率很低,
# 应把 KDTree 提到模块级只建一次。
kdt_db = KDTree(rgb_values)
# query(点):返回 (最近距离, 最近点下标)。
distance, index = kdt_db.query(rgb_tuple)
# 用下标取名字,.title() 首字母大写更好看。
return names[index].title()


# 复制到剪贴板。
def copy_to_clipboard():
# Text.get('1.0', END):从第 1 行第 0 列取到末尾(Tk 的索引格式是 '行.列')。
# 注意 END 会多带一个换行,属正常。
root.clipboard_append(colors_text.get("1.0", END))


# 清空文本框。
def clear_text():
# delete('1.0', END):整段删除。
colors_text.delete("1.0", END)


# 主窗口与控件装配。
root = Tk()
root.title('Image to Color List')
root.config(padx=25, pady=25, bg=BACKGROUND_COLOR)
title_label = Label(text="Image to Color List", font=(TITLE_FONT, 32, "bold"), fg=TITLE_COLOR, bg=BACKGROUND_COLOR)
open_btn = Button(text="Select Image", font=(WORD_FONT, 20), width=25, fg=WORD_COLOR, bg=BTN_BACKGROUND_COLOR,
command=get_img_colors)
copy_btn = Button(text="Copy Text", font=(WORD_FONT, 20), width=25, fg=WORD_COLOR, bg=BTN_BACKGROUND_COLOR,
command=copy_to_clipboard)
clear_btn = Button(text="Clear Text", font=(WORD_FONT, 20), width=25, fg=WORD_COLOR, bg=BTN_BACKGROUND_COLOR,
command=clear_text)
# Text:多行文本区,width/height 以字符为单位。
colors_text = Text(root, width=35, height=16, font=(TITLE_FONT, 14))
title_label.grid(column=0, row=0, pady=20)
colors_text.grid(column=0, row=1)
open_btn.grid(column=0, row=2, pady=10)
copy_btn.grid(column=0, row=3)
clear_btn.grid(column=0, row=4, pady=10)
# 事件循环。
root.mainloop()

代码走读

  1. NUMBER_OF_COLORS = 15 限制输出条数。
  2. get_img_colors():选图 → Image.open(...).convert('RGB')(统一成 RGB,避免 RGBA/灰度出错)→ palette(img) 拿到按频率排序的颜色 → 逐个转名字 → 去重且不超过 15 个 → 插入文本框。
  3. palette() + asvoid():核心算法(见上)。
  4. convert_rgb_to_names():KD 树最近邻。
  5. copy_to_clipboard() / clear_text():两个按钮的回调。
  6. UI:标题、文本框、三个按钮纵向排列。

这份代码的问题

(1) 每次转换都重建 KD 树

1
2
for code in color_codes:
if convert_rgb_to_names(code) not in color_names ...

convert_rgb_to_names 里 KDTree(rgb_values) 每次新建。图片大、颜色多时明显变慢。应该模块级建一次。

(2) 同一个颜色算了两遍

1
2
3
if convert_rgb_to_names(code) not in color_names and len(color_names) < NUMBER_OF_COLORS:
color_names.append(convert_rgb_to_names(code))
colors_text.insert(END, convert_rgb_to_names(code) + 'n')

一次循环调了 3 次同一个函数。应该先 name = convert_rgb_to_names(code)。

(3) palette() 返回全部颜色

一张照片可能有几万种颜色,palette 全算一遍(np.unique + bincount),然后只取前 15 —— 浪费。可以先 img.resize((100,100)) 降采样,或 img.quantize(colors=15)。

(4) Text 没设 state='disabled'

用户可以直接在结果框里乱改。只读展示应该 state=DISABLED(插入前后切换)。

(5) copy_to_clipboard 复制了末尾换行

get("1.0", END) 会带一个 n,粘出来多一空行。用 get("1.0", "end-1c")。

(6) 没有异常处理

选了非图片文件、超大图,都会崩。

运行结果

深色窗口,标题 "Image to Color List",一个大文本框,下面三个按钮。选一张风景照 → 文本框列出 15 行颜色名:Darkslategray、Skyblue、Whitesmoke…… → 点 Copy Text 复制到剪贴板 → 点 Clear Text 清空。

易错点

  1. Text 用整数索引:get(0, END) 报错,必须 get("1.0", END)。
  2. webcolors 新版 API 变了:CSS3_HEX_TO_NAMES 在新版可能被移到 webcolors.css3 子模块,导入失败就 pip install webcolors==1.11.1。
  3. RGBA 图片:convert('RGB') 必须加,否则 reshape(-1, 4) 和 3 通道不匹配。
  4. np.unique 直接作用于三维数组:会按"展平后每个元素"去重,得到的是单个通道值,不是颜色。

动手改

  • 把 KD 树提到模块级,只建一次。
  • 每个颜色只转一次名。
  • 降采样到 200×200 再统计,速度提升几十倍。
  • 结果框设只读,加"复制十六进制色值"按钮。

源文件逐个讲解

3 个文件:

文件 规模 职责
main.py98 行从图片里提取「主色调」,并翻译成颜色名
image.png示例图用来测试的图片
README.md8 行说明页

这一天的技术含量是「第 5 阶段最高」的——三行核心代码用到了 np.unique + asvoid + bincount 的组合技巧(这是「按整行去重」的 NumPy 高级用法)。

main.py(98 行)

(1)五个导入

1
2
3
4
5
6
7
8
9
from tkinter import *
from tkinter import filedialog
import numpy as np
from PIL import Image
from scipy.spatial import KDTree
from webcolors import (
CSS3_HEX_TO_NAMES,
hex_to_rgb,
)
库 用途
tkinter界面
numpy统计「每个颜色出现几次」
PIL读图
scipy.spatial.KDTree「最近的邻居」查询(找最像的 CSS 颜色)
webcolors140 个 CSS3 颜色名 + 十六进制转 RGB

KDTree 是这一天的「新武器」——它是一个「多维空间索引」,能在 140 个 RGB 点里秒找「离目标最近的那个」。

(2)get_img_colors():主流程

1
2
3
4
5
6
7
8
9
10
11
12
13
def get_img_colors():
img_file = filedialog.askopenfilename(
initialdir="/",
title="Select IMG",
filetypes=(('Image Files', "*.jpg;*.jpeg;*.png"), ("All Files", "*.*"))
)
img = Image.open(img_file, 'r').convert('RGB')
color_codes = palette(img)
color_names = []
for code in color_codes:
if convert_rgb_to_names(code) not in color_names and len(color_names) < NUMBER_OF_COLORS:
color_names.append(convert_rgb_to_names(code))
colors_text.insert(END, convert_rgb_to_names(code) + 'n')

四步:

步 代码 作用
1askopenfilename(...)选图
2Image.open(...).convert('RGB')读图 + 统一转 RGB
3palette(img)拿到「按出现次数降序」的颜色列表
4循环 + 去重 + 限 15 个转成颜色名,写进文本框

convert('RGB') 是关键:

PNG 可能是 RGBA(4 通道)或 P(调色板模式)——不转 RGB,后面 arr.shape[-1] 会得到 4 或 1,颜色比较就错了。

(3)filetypes 的写法是错的

1
filetypes=(('Image Files', "*.jpg;*.jpeg;*.png"), ("All Files", "*.*"))

"*.jpg;*.jpeg;*.png" 在 Tkinter 里「不是一个有效通配符」——Tk 用的是「空格分隔」不是「分号」。

正确写法:

1
filetypes=(("Image Files", "*.jpg *.jpeg *.png"), ("All Files", "*.*"))

用分号的话,很可能「一个文件都显示不出来」(只剩「All Files」能用)。

(4)palette():全书最巧的一段

1
2
3
4
5
6
7
8
9
10
def palette(img):
"""
Return palette in descending order of frequency
"""
arr = np.asarray(img)
palette, index = np.unique(asvoid(arr).ravel(), return_inverse=True)
palette = palette.view(arr.dtype).reshape(-1, arr.shape[-1])
count = np.bincount(index)
order = np.argsort(count)
return palette[order[::-1]]

目标:「统计这张图里,每个 RGB 三元组出现了多少次,按次数降序排」。

难点:np.unique 只能对「一维数组」去重——而图片是 (高, 宽, 3) 的三维数组。

三行代码解决:

① asvoid(arr).ravel():把「每个像素的 3 个字节」压成「一个 void 标量」

asvoid 把 (H, W, 3) 的 uint8 数组「重新解释」成 (H, W, 1) 的「3 字节 void 类型」——每个像素变成「一个不可分割的整体」。

这样才能「按像素整体去重」而不是「按单个通道值去重」。

② np.unique(..., return_inverse=True)

返回两个东西:

  • palette:所有不重复的「void 像素」(降序排列)
  • index:原数组每个位置「对应 palette 里的第几个」

③ palette.view(arr.dtype).reshape(-1, 3)

把「void 数组」再「看回」uint8——每个 void 变回 3 个字节——reshape(-1, 3) 得到 (颜色数, 3)。

④ np.bincount(index)

index 里每个值就是「某个颜色的编号」——bincount 统计「每个编号出现几次」。

这是「计数器」的标准写法:输入「一堆 0~N 的整数」,输出「长度为 N+1 的计数数组」。

⑤ np.argsort(count) + [::-1]

argsort 返回「从小到大排序后的下标」——[::-1] 反转成「从大到小」。

⑥ palette[order]

用「排好序的下标」去取颜色——得到「按频率降序的颜色列表」。

(5)asvoid():一段「抄来的」代码

1
2
3
4
5
6
7
8
def asvoid(arr):
"""View the array as dtype np.void (bytes)
This collapses ND-arrays to 1D-arrays, so you can perform 1D operations on them.
http://stackoverflow.com/a/16216866/190597 (Jaime)
...
"""
arr = np.ascontiguousarray(arr)
return arr.view(np.dtype((np.void, arr.dtype.itemsize * arr.shape[-1])))

np.ascontiguousarray(arr):保证内存连续——view 要求「连续内存」(否则报错)。

arr.view(np.dtype((np.void, 每像素字节数))):

np.dtype((np.void, 3)) 表示「3 个字节的 void 类型」——view 把 (H,W,3) 的 uint8「重新解释」成 (H,W) 的「3 字节块」。

⚠️ 函数注释里诚实写了出处(StackOverflow 的两个链接 + 作者 Jaime)——这是好习惯。

⚠️ 注释里的「Warning」也很有价值:

asvoid([-0.]) == asvoid([0.]) 返回 False

因为「-0.0 和 0.0 的「字节表示」不同」(浮点的符号位)——所以「按字节比较」会认为它们不等。

对图片(uint8)没有这个问题,但对浮点数组要小心。

(6)convert_rgb_to_names():KDTree 找最近色

1
2
3
4
5
6
7
8
9
10
11
12
def convert_rgb_to_names(rgb_tuple):
# A dictionary of all the hex and their respective names in css3
css3_db = CSS3_HEX_TO_NAMES
names = []
rgb_values = []
for color_hex, color_name in css3_db.items():
names.append(color_name)
rgb_values.append(hex_to_rgb(color_hex))

kdt_db = KDTree(rgb_values)
distance, index = kdt_db.query(rgb_tuple)
return names[index].title()

三步:

  1. 把 140 个 CSS3 颜色拆成「名字列表」+「RGB 列表」;
  2. 用 RGB 列表建 KDTree;
  3. query(rgb_tuple) 找「最近的邻居」,返回它的下标。

KDTree 是「K 维树」——一种「空间索引」,能在 O(log n) 时间里找「离目标点最近的已有数据点」。

query() 返回两个值:

返回值 含义
distance最近点的距离(这里没用,用 _ 忽略更好)
index最近点的下标

.title():把 "dark slate blue" 变成 "Dark Slate Blue"——首字母大写,好看。

⚠️ 真 bug:KDTree 在「循环里被重建」

palette() 返回的可能有几千种颜色,每处理一个颜色,就「重新建一次 KDTree」——建树的成本是 O(n log n),循环 1000 次 = 极其浪费。

正确做法:把 KDTree 提到「模块级」,只建一次。

1
2
3
_RGB_VALUES = [hex_to_rgb(h) for h in CSS3_HEX_TO_NAMES]
_NAMES = list(CSS3_HEX_TO_NAMES.values())
_KD = KDTree(_RGB_VALUES)

这是「把不变的计算移到循环外」的经典优化。

⚠️ 另一个真 bug:convert_rgb_to_names(code) 被调用了三次

1
2
3
if convert_rgb_to_names(code) not in color_names and len(color_names) < NUMBER_OF_COLORS:
color_names.append(convert_rgb_to_names(code))
colors_text.insert(END, convert_rgb_to_names(code) + 'n')

同一个值算三次——每次都要「遍历 140 个颜色 + 建树 + 查询」。

应该先存进变量:

1
2
3
4
name = convert_rgb_to_names(code)
if name not in color_names and len(color_names) < NUMBER_OF_COLORS:
color_names.append(name)
colors_text.insert(END, name + "n")

(7)剪贴板与清空

1
2
3
4
5
def copy_to_clipboard():
root.clipboard_append(colors_text.get("1.0", END))

def clear_text():
colors_text.delete("1.0", END)

Text 控件的「索引」语法:

索引 含义
"1.0"第 1 行、第 0 个字符(即开头)
END末尾

get("1.0", END):取「从头到尾」的全部文字。 delete("1.0", END):全删。

⚠️ clipboard_append 之后要 root.update() 才能真正写入系统剪贴板(某些平台需要)——否则「复制完粘贴不出来」。

(8)界面

1
2
3
4
5
6
colors_text = Text(root, width=35, height=16, font=(TITLE_FONT, 14))
title_label.grid(column=0, row=0, pady=20)
colors_text.grid(column=0, row=1)
open_btn.grid(column=0, row=2, pady=10)
copy_btn.grid(column=0, row=3)
clear_btn.grid(column=0, row=4, pady=10)

五行单列布局:

行 控件
0标题
1多行文本框(35 字符宽 × 16 行高)
2Select Image
3Copy Text
4Clear Text

Text vs Entry:Text 是多行、Entry 是单行——这里要显示 15 个颜色名,必须用 Text。

⚠️ 没有滚动条:如果颜色名超过 16 行,多出来的「看不到也滚不动」(虽然代码限制了 15 个,刚好)。

这份代码的问题

  1. filetypes 用分号分隔(Tk 不认,应空格)。
  2. KDTree 在循环里被重建 N 次(性能灾难)。
  3. convert_rgb_to_names() 被调用三次(同一个值算三遍)。
  4. clipboard_append 后没有 update()(某些平台复制不生效)。
  5. initialdir="/"(起点是根目录)。
  6. Text 没有滚动条。
  7. distance 返回值没用到(应写 _, index =)。
  8. 没有「显示颜色方块」(只有名字,看不到实际颜色)。
  9. 没有 try/except(选了非图片文件就崩)。
  10. 没有 if __name__ == "__main__"。

image.png

一张示例图——用来验证「提取主色调」的效果。

代码里没有引用它(是用户手动在对话框里选的)——它只是「测试素材」。

README.md(8 行)

标题 Day 91 - Image Colour Palette Generator,知识点:Tkinter、NumPy、PIL、KDTree、Color Theory。

五个:Tkinter、NumPy、PIL、KDTree、色彩理论。

这一天把「Day 65 的色彩理论」和「Day 76 的图片即数组」接上了:

前面学的 这里用来
Day 76:图片 = (H,W,3) 数组np.asarray(img)
Day 76:通道是数字RGB 三元组当「三维坐标」
Day 65:色彩理论「主色提取」的实际用途
Day 78:value_counts 思想np.bincount 数颜色

而 KDTree 是全新的东西——「在 140 个已知颜色里找最像的那个」。

这是「最近邻搜索」的最小案例——它的「大版本」就是「以图搜图」、「推荐系统」、「向量数据库」。

微信收款码 微信
支付宝收款码 支付宝
评论