import cv2
import numpy as np
from collections import Counter
from sklearn.cluster import KMeans

# 读取图片
image_path = "111.png"  # 替换为你的图片路径
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# 将图像转换为一维数组
pixels = image.reshape(-1, 3)

# 使用 KMeans 进行颜色聚类
num_colors = 20  # 选取主要的 10 种颜色
kmeans = KMeans(n_clusters=num_colors, n_init=10)
kmeans.fit(pixels)

# 获取颜色分布
colors = kmeans.cluster_centers_.astype(int)
labels = kmeans.labels_
color_counts = Counter(labels)
total_pixels = len(pixels)

# 计算颜色比例
color_ratios = {tuple(colors[i]): count / total_pixels for i, count in color_counts.items()}

# 生成 HTML 文件
html_content = """
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>颜色占比</title>
    <style>
        .color-box {
            display: inline-block;
            width: 150px;
            height: 150px;
            text-align: center;
            line-height: 150px;
            font-size: 18px;
            font-weight: bold;
            color: white;
            margin: 10px;
            border-radius: 10px;
        }
    </style>
</head>
<body>
    <h1>图片颜色占比分析</h1>
"""

# 添加颜色块
for color, ratio in sorted(color_ratios.items(), key=lambda x: x[1], reverse=True):
    hex_color = "#{:02x}{:02x}{:02x}".format(*color)
    text_color = "black" if sum(color) > 400 else "white"  # 根据亮度调整字体颜色
    html_content += f'<div class="color-box" style="background-color:{hex_color}; color:{text_color};">{ratio:.2%}</div>'

html_content += "</body></html>"

# 保存为 HTML 文件
with open("color_analysis.html", "w", encoding="utf-8") as f:
    f.write(html_content)

print("HTML 文件已生成：color_analysis.html")