從影像擷取 RGB 數值
要找出影像中的主色,大致分成三個步驟:
- 將 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)