从图像中提取 RGB 值
要在一张图像中找到主色调,大致分为 3 个步骤:
- 将 RGB 数值提取到三个列表中。
- 对缩放后的 RGB 值执行 k-means 聚类。
- 显示聚类中心对应的颜色。
为了提取 RGB 值,我们使用 matplotlib 的 image 类中的 imread() 函数。空列表 r、g 和 b 已经初始化。
为寻找主色调,我们将使用下图所示的图像。

本练习是课程的一部分
Python 中的聚类分析
练习说明
- 导入
matplotlib的image类。 - 使用
imread()函数读取图像,并打印结果矩阵的维度。 - 将所有像素的三种颜色通道值分别存入列表
r、g和b。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Import image class of matplotlib
____ as img
# Read batman image and print dimensions
batman_image = ____('batman.jpg')
print(____)
# Store RGB values of all pixels in lists r, g and b
for ____:
for temp_r, temp_g, temp_b in ____:
r.append(temp_r)
g.append(temp_g)
b.append(temp_b)