Created
July 23, 2021 15:32
-
-
Save zjuyk/92f1c3776be2c87e06b34e5ba5151ada to your computer and use it in GitHub Desktop.
提取图片主要颜色脚本
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import matplotlib.image as img | |
import pandas as pd | |
from scipy.cluster.vq import whiten, kmeans | |
target_image = img.imread("path/to/target_image") | |
r = [] | |
g = [] | |
b = [] | |
for row in target_image: | |
for temp_r, temp_g, temp_b in row: | |
r.append(temp_r) | |
g.append(temp_g) | |
b.append(temp_b) | |
image_df = pd.DataFrame({'red': r, | |
'green': g, | |
'blue': b}) | |
# scale image information | |
image_df['scaled_color_red'] = whiten(image_df['red']) | |
image_df['scaled_color_blue'] = whiten(image_df['blue']) | |
image_df['scaled_color_green'] = whiten(image_df['green']) | |
cluster_centers, _ = kmeans(image_df[['scaled_color_red', | |
'scaled_color_blue', | |
'scaled_color_green']], 3) | |
dominant_colors = [] | |
# Get standard deviations of each color | |
red_std, green_std, blue_std = image_df[['red', | |
'green', | |
'blue']].std() | |
for cluster_center in cluster_centers: | |
red_scaled, green_scaled, blue_scaled = cluster_center | |
# Convert each standardized value to scaled value | |
dominant_colors.append(( | |
red_scaled * red_std, | |
green_scaled * green_std, | |
blue_scaled * blue_std | |
)) | |
print(dominant_colors) |
实际上可以先对图片大小进行压缩,例如压缩到 200x200的尺寸,颜色信息相差也不会很大
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
使用的是 scipy 的 kmeans 函数,对于比较大的图片可能要算上蛮久