一、前言对图片进行颜色分析,为您提供图片中的主要颜色以及其相应的出现频率。具体来说,将执行以下步骤:- 将图片转换为RGB颜色空间。
- 聚类方法对颜色进行分类。
- 找到每个聚类的中心,这可以代表该聚类的主要颜色。
- 根据每个聚类中的像素数量,确定每种颜色的出现频率。
二、代码
[Python] 纯文本查看 复制代码 from sklearn.cluster import KMeans
import numpy as np
from PIL import Image
# Define the number of colors to extract
n_colors = 5
image_path = r"D:\Desktop\tp.png"
img = Image.open(image_path)
# Convert image to RGB array
img_array = np.array(img)
img_array = img_array.reshape((img_array.shape[0] * img_array.shape[1], 3))
# Use KMeans clustering to find most dominant colors
kmeans = KMeans(n_clusters=n_colors)
kmeans.fit(img_array)
# Get the RGB values of the centroids
centroids = kmeans.cluster_centers_
# Count the number of pixels associated with each cluster
histogram = np.histogram(kmeans.labels_, bins=n_colors, range=(0, n_colors))
# Calculate the percentage of each color
percentages = (histogram[0] / img_array.shape[0]) * 100
# Sort colors by percentage in descending order
sorted_indices = np.argsort(percentages)[::-1]
sorted_centroids = centroids[sorted_indices]
sorted_percentages = percentages[sorted_indices]
colors_list = []
# Print the dominant colors and their percentages in descending order
for i in range(n_colors):
color_info = {}
color_info["rgb"] = f"RGB({sorted_centroids[i][0]:.0f}, {sorted_centroids[i][1]:.0f}, {sorted_centroids[i][2]:.0f})"
color_info["percentage"] = sorted_percentages[i]
colors_list.append(color_info)
print(
f"Color {i + 1}: RGB({sorted_centroids[i][0]:.0f}, {sorted_centroids[i][1]:.0f}, {sorted_centroids[i][2]:.0f}) - {sorted_percentages[i]:.2f}%")
print("*******************************************")
print(colors_list)
三、结果
[Python] 纯文本查看 复制代码 Color 1: RGB(142, 110, 86) - 24.22%
Color 2: RGB(183, 158, 134) - 23.22%
Color 3: RGB(88, 64, 50) - 22.36%
Color 4: RGB(39, 24, 18) - 19.14%
Color 5: RGB(230, 215, 197) - 11.06%
*******************************************
[{'rgb': 'RGB(142, 110, 86)', 'percentage': 24.223709106445312}, {'rgb': 'RGB(183, 158, 134)', 'percentage': 23.224353790283203}, {'rgb': 'RGB(88, 64, 50)', 'percentage': 22.359180450439453}, {'rgb': 'RGB(39, 24, 18)', 'percentage': 19.1375732421875}, {'rgb': 'RGB(230, 215, 197)', 'percentage': 11.055183410644531}] |