使用的图片
准备
# 相关库
from PIL import Image
import pandas as pd
import numpy as np
# 打开图片
img = Image.open(img_path)
运行
pd.Series([','.join(j) for i in np.array(img).astype('str') for j in i]).value_counts()[:5]
前5种
147,156,189 67
150,155,185 53
149,147,160 52
154,151,168 50
151,156,186 44
dtype: int64
到这里就完成要求了。下面把前1000种颜色从左到右显示出来
前1000种
img = Image.open(img_path)
img_data = np.array(img).astype('str') # 字符串方便join
flat_data = [','.join(j) for i in img_data for j in i] # 压缩
out = pd.Series(flat_data)
num = 1000 # 显示颜色数量
plt.figure(figsize=(10, 1))
ax = plt.gca()
for n, color in enumerate(out.value_counts().index[:num]):
color = np.array([int(i) for i in color.split(',')]) / 255 # 转换成0-1的rgb
ax.add_patch(plt.Rectangle((n, 0), 1, 1, color=color)) # 画竖条
plt.xlim(0, num)