一、前言
对图片进行颜色分析,为您提供图片中的主要颜色以及其相应的出现频率。
具体来说,将执行以下步骤:
- 将图片转换为RGB颜色空间。
- 聚类方法对颜色进行分类。
- 找到每个聚类的中心,这可以代表该聚类的主要颜色。
- 根据每个聚类中的像素数量,确定每种颜色的出现频率。
二、代码
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 perce