Commit
·
2968ea0
1
Parent(s):
600781e
first commit
Browse files- .vscode/settings.json +5 -0
- LICENSE +21 -0
- README.md +65 -0
- app.py +9 -0
- palette_app.py +406 -0
- requirements.txt +4 -0
.vscode/settings.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"python-envs.defaultEnvManager": "ms-python.python:conda",
|
| 3 |
+
"python-envs.defaultPackageManager": "ms-python.python:conda",
|
| 4 |
+
"python-envs.pythonProjects": []
|
| 5 |
+
}
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2025 WilliamZ
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
CHANGED
|
@@ -12,3 +12,68 @@ short_description: 快速提取图片调色板并使用UI可视化
|
|
| 12 |
---
|
| 13 |
|
| 14 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
---
|
| 13 |
|
| 14 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
| 15 |
+
|
| 16 |
+
# Palette Explorer
|
| 17 |
+
|
| 18 |
+
一款交互式 Gradio 应用,可从任意图片中提取主色调,通过带复制按钮的排版卡片展示结果,并在 RGB 三维空间中可视化 k-means 聚类分布。
|
| 19 |
+
|
| 20 |
+
## 功能特点
|
| 21 |
+
- 使用可配置数量的 k-means 聚类提取主色调,并支持随机种子复现结果。
|
| 22 |
+
- 生成平滑的渐变带与排版预览卡片,提供一键复制 HEX 颜色码。
|
| 23 |
+
- 在交互式 Plotly 三维散点图中查看采样像素与聚类中心的 RGB 分布。
|
| 24 |
+
- 以结构化 JSON 展示调色板数据,便于二次处理。
|
| 25 |
+
- 提供命令行模式,无需启动界面即可快速导出调色信息。
|
| 26 |
+
|
| 27 |
+
## 快速上手
|
| 28 |
+
|
| 29 |
+
### 1. 本地(Conda 环境)
|
| 30 |
+
```
|
| 31 |
+
conda activate pytorch
|
| 32 |
+
python palette_app.py --ui
|
| 33 |
+
```
|
| 34 |
+
Gradio 会在终端输出访问地址(默认 `http://127.0.0.1:7860`)。
|
| 35 |
+
|
| 36 |
+
### 2. 命令行调色板提取
|
| 37 |
+
```
|
| 38 |
+
python palette_app.py -n 8 path/to/image.jpg
|
| 39 |
+
```
|
| 40 |
+
终端将输出颜色的 HEX、RGB 值及占比信息。
|
| 41 |
+
|
| 42 |
+
### 3. Docker
|
| 43 |
+
手动构建(GitHub Action 在 `main` 分支上会自动构建):
|
| 44 |
+
```
|
| 45 |
+
docker build -t palette-app .
|
| 46 |
+
docker run -p 7860:7860 palette-app
|
| 47 |
+
```
|
| 48 |
+
浏览器访问 `http://localhost:7860` 查看应用。
|
| 49 |
+
|
| 50 |
+
## 项目结构
|
| 51 |
+
```
|
| 52 |
+
.
|
| 53 |
+
├─ palette_app.py # Gradio / CLI 主入口
|
| 54 |
+
├─ requirements.txt # 运行时依赖
|
| 55 |
+
├─ Dockerfile # 部署用容器定义
|
| 56 |
+
├─ .dockerignore # Docker 构建忽略列表
|
| 57 |
+
└─ .github/workflows/
|
| 58 |
+
└─ deploy.yml # 构建并推送镜像到 GHCR 的 GitHub Action
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
## GitHub Actions 部署
|
| 62 |
+
工作流 `.github/workflows/deploy.yml` 会在推送到 `main`(或手动触发)时执行:
|
| 63 |
+
1. 安装依赖并运行烟雾测试(`python -m compileall palette_app.py`)。
|
| 64 |
+
2. 构建 Docker 镜像。
|
| 65 |
+
3. 推送镜像到 `ghcr.io/<owner>/palette-app:latest`(需启用 GitHub Packages 权限)。
|
| 66 |
+
|
| 67 |
+
在其他环境拉取已发布镜像:
|
| 68 |
+
```
|
| 69 |
+
docker login ghcr.io
|
| 70 |
+
docker pull ghcr.io/<owner>/palette-app:latest
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
## 开发提示
|
| 74 |
+
- 若不使用 Conda,可执行 `pip install -r requirements.txt` 安装依赖。
|
| 75 |
+
- 三维散点依赖 Plotly,若在无图形界面的服务器运行,可考虑导出静态文件或使用具备浏览器的环境。
|
| 76 |
+
- 若需本地化或自定义文案,可修改 `palette_app.py` 中 `_typography_html` 的短句与复制按钮行为。
|
| 77 |
+
|
| 78 |
+
## 许可证
|
| 79 |
+
请在此填写项目适用的许可证(如 MIT、Apache-2.0 等)。
|
app.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from palette_app import launch_demo
|
| 2 |
+
|
| 3 |
+
launch_demo(
|
| 4 |
+
default_num_colors=5,
|
| 5 |
+
default_seed=42,
|
| 6 |
+
share=False,
|
| 7 |
+
server_name=None,
|
| 8 |
+
server_port=None,
|
| 9 |
+
)
|
palette_app.py
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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1 |
+
"""Interactive color palette extractor and demo.
|
| 2 |
+
|
| 3 |
+
This script loads an image, extracts a palette with a configurable
|
| 4 |
+
number of colors, and showcases the palette inside a Gradio interface
|
| 5 |
+
using multiple visual styles (gradient bar and card layout).
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
from typing import List, Sequence, Tuple
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
from PIL import Image
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
import gradio as gr
|
| 18 |
+
except ImportError as exc: # pragma: no cover - handled when running the UI
|
| 19 |
+
raise ImportError(
|
| 20 |
+
"Gradio is required to run the interactive demo."
|
| 21 |
+
) from exc
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
import plotly.graph_objects as go
|
| 25 |
+
except ImportError as exc: # pragma: no cover - plotting is optional
|
| 26 |
+
raise ImportError(
|
| 27 |
+
"Plotly is required for the 3D scatter visualization. Install it via `pip install plotly`."
|
| 28 |
+
) from exc
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass
|
| 32 |
+
class PaletteColor:
|
| 33 |
+
"""Container for palette metadata."""
|
| 34 |
+
|
| 35 |
+
rgb: Tuple[int, int, int]
|
| 36 |
+
percentage: float
|
| 37 |
+
|
| 38 |
+
@property
|
| 39 |
+
def hex(self) -> str:
|
| 40 |
+
return "#" + "".join(f"{channel:02X}" for channel in self.rgb)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@dataclass
|
| 44 |
+
class PaletteResult:
|
| 45 |
+
"""Aggregated palette data and clustering artifacts."""
|
| 46 |
+
|
| 47 |
+
colors: List[PaletteColor]
|
| 48 |
+
samples: np.ndarray
|
| 49 |
+
labels: np.ndarray
|
| 50 |
+
centroids: np.ndarray
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _prepare_pixels(image: Image.Image, max_sample: int = 5000) -> np.ndarray:
|
| 54 |
+
"""Convert an image into a 2D array of pixels and optionally subsample."""
|
| 55 |
+
|
| 56 |
+
if image.mode not in {"RGB", "RGBA"}:
|
| 57 |
+
image = image.convert("RGB")
|
| 58 |
+
|
| 59 |
+
pixels = np.array(image)
|
| 60 |
+
if pixels.ndim == 3 and pixels.shape[2] == 4: # strip alpha channel
|
| 61 |
+
pixels = pixels[:, :, :3]
|
| 62 |
+
|
| 63 |
+
flat_pixels = pixels.reshape(-1, 3).astype(np.float32)
|
| 64 |
+
|
| 65 |
+
if len(flat_pixels) > max_sample:
|
| 66 |
+
rng = np.random.default_rng(42)
|
| 67 |
+
indices = rng.choice(len(flat_pixels), size=max_sample, replace=False)
|
| 68 |
+
flat_pixels = flat_pixels[indices]
|
| 69 |
+
|
| 70 |
+
return flat_pixels
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _kmeans(
|
| 74 |
+
pixels: np.ndarray,
|
| 75 |
+
num_colors: int,
|
| 76 |
+
*,
|
| 77 |
+
max_iter: int = 25,
|
| 78 |
+
tol: float = 1e-2,
|
| 79 |
+
seed: int | None = None,
|
| 80 |
+
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 81 |
+
"""Simple k-means clustering implementation for RGB pixels."""
|
| 82 |
+
|
| 83 |
+
if len(pixels) == 0:
|
| 84 |
+
raise ValueError("No pixels available for clustering")
|
| 85 |
+
|
| 86 |
+
num_colors = max(1, min(num_colors, len(pixels)))
|
| 87 |
+
|
| 88 |
+
rng = np.random.default_rng(seed)
|
| 89 |
+
initial_indices = rng.choice(len(pixels), size=num_colors, replace=False)
|
| 90 |
+
centroids = pixels[initial_indices]
|
| 91 |
+
|
| 92 |
+
for _ in range(max_iter):
|
| 93 |
+
distances = np.linalg.norm(pixels[:, None, :] - centroids[None, :, :], axis=2)
|
| 94 |
+
labels = np.argmin(distances, axis=1)
|
| 95 |
+
|
| 96 |
+
new_centroids = np.vstack(
|
| 97 |
+
[pixels[labels == idx].mean(axis=0) if np.any(labels == idx) else centroids[idx]
|
| 98 |
+
for idx in range(num_colors)]
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
shift = np.linalg.norm(new_centroids - centroids)
|
| 102 |
+
centroids = new_centroids
|
| 103 |
+
|
| 104 |
+
if shift < tol:
|
| 105 |
+
break
|
| 106 |
+
|
| 107 |
+
counts = np.array([(labels == idx).sum() for idx in range(num_colors)], dtype=np.int32)
|
| 108 |
+
order = np.argsort(counts)[::-1]
|
| 109 |
+
remap = np.empty_like(order)
|
| 110 |
+
remap[order] = np.arange(num_colors)
|
| 111 |
+
remapped_labels = remap[labels]
|
| 112 |
+
return centroids[order], counts[order], remapped_labels
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def extract_palette(
|
| 116 |
+
image_source: Image.Image | np.ndarray | str,
|
| 117 |
+
num_colors: int,
|
| 118 |
+
seed: int | None = None,
|
| 119 |
+
) -> PaletteResult:
|
| 120 |
+
"""Extract a color palette with num_colors entries from the image."""
|
| 121 |
+
|
| 122 |
+
if isinstance(image_source, Image.Image):
|
| 123 |
+
image = image_source
|
| 124 |
+
elif isinstance(image_source, np.ndarray):
|
| 125 |
+
image = Image.fromarray(image_source.astype(np.uint8))
|
| 126 |
+
elif isinstance(image_source, str):
|
| 127 |
+
image = Image.open(image_source)
|
| 128 |
+
else:
|
| 129 |
+
raise TypeError("Unsupported image source type")
|
| 130 |
+
|
| 131 |
+
pixels = _prepare_pixels(image)
|
| 132 |
+
centroids, counts, labels = _kmeans(pixels, num_colors, seed=seed)
|
| 133 |
+
|
| 134 |
+
total = counts.sum()
|
| 135 |
+
palette = []
|
| 136 |
+
for centroid, count in zip(centroids, counts):
|
| 137 |
+
rounded = np.clip(np.round(centroid), 0, 255).astype(np.uint8)
|
| 138 |
+
palette.append(PaletteColor(tuple(int(channel) for channel in rounded), count / total))
|
| 139 |
+
|
| 140 |
+
return PaletteResult(colors=palette, samples=pixels, labels=labels, centroids=centroids)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _gradient_html(palette: Sequence[PaletteColor]) -> str:
|
| 144 |
+
"""Create a CSS gradient bar to display the palette smoothly."""
|
| 145 |
+
|
| 146 |
+
if not palette:
|
| 147 |
+
return "<div>暂无调色数据</div>"
|
| 148 |
+
|
| 149 |
+
stops = []
|
| 150 |
+
total = len(palette) - 1 or 1
|
| 151 |
+
for idx, color in enumerate(palette):
|
| 152 |
+
percent = (idx / total) * 100
|
| 153 |
+
stops.append(f"{color.hex} {percent:.2f}%")
|
| 154 |
+
|
| 155 |
+
gradient = ", ".join(stops)
|
| 156 |
+
return f"<div style=\"height: 48px; border-radius: 8px; border: 1px solid #d1d5db; background: linear-gradient(90deg, {gradient});\"></div>"
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _relative_luminance(rgb: Tuple[int, int, int]) -> float:
|
| 160 |
+
"""Calculate the WCAG relative luminance for an RGB tuple."""
|
| 161 |
+
|
| 162 |
+
def _channel_linear(value: int) -> float:
|
| 163 |
+
srgb = value / 255
|
| 164 |
+
return srgb / 12.92 if srgb <= 0.03928 else ((srgb + 0.055) / 1.055) ** 2.4
|
| 165 |
+
|
| 166 |
+
r, g, b = rgb
|
| 167 |
+
return 0.2126 * _channel_linear(r) + 0.7152 * _channel_linear(g) + 0.0722 * _channel_linear(b)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _typography_html(palette: Sequence[PaletteColor]) -> str:
|
| 171 |
+
"""Show typography samples on colored backgrounds."""
|
| 172 |
+
|
| 173 |
+
if not palette:
|
| 174 |
+
return "<div>暂无调色数据</div>"
|
| 175 |
+
|
| 176 |
+
previews = []
|
| 177 |
+
phrases = [
|
| 178 |
+
"用色彩描绘心境",
|
| 179 |
+
"颜色是灵魂的触觉",
|
| 180 |
+
"色彩即语言"
|
| 181 |
+
]
|
| 182 |
+
for idx, color in enumerate(palette[:6]):
|
| 183 |
+
luminance = _relative_luminance(color.rgb)
|
| 184 |
+
text_hex = "#101321" if luminance > 0.55 else "#F5F7FF"
|
| 185 |
+
secondary_hex = "#2E3143" if luminance > 0.55 else "#D8E2FF"
|
| 186 |
+
phrase = phrases[idx % len(phrases)]
|
| 187 |
+
button = (
|
| 188 |
+
f"<button type='button' style=\"float:right;margin-bottom:0.6rem;padding:0.3rem 0.6rem;"
|
| 189 |
+
"border:1px solid rgba(17,24,39,0.2);border-radius:6px;background-color:rgba(255,255,255,0.8);"
|
| 190 |
+
"font-size:0.75rem;cursor:pointer;\""
|
| 191 |
+
f" onclick=\"navigator.clipboard.writeText('{color.hex}');"
|
| 192 |
+
"this.textContent='已复制';setTimeout(()=>this.textContent='复制 HEX',1200);\">复制 HEX</button>"
|
| 193 |
+
)
|
| 194 |
+
previews.append(
|
| 195 |
+
"<div style=\"border:1px solid #d1d5db;border-radius:8px;padding:0.8rem;"
|
| 196 |
+
f"background:{color.hex};color:{text_hex};margin-bottom:0.6rem;position:relative;overflow:hidden;\">"
|
| 197 |
+
f" {button}"
|
| 198 |
+
f" <div style=\"font-weight:600;\">{phrase}</div>"
|
| 199 |
+
f" <div style=\"font-size:0.85rem;color:{secondary_hex};margin-top:0.2rem;\">{color.hex} · {color.rgb}</div>"
|
| 200 |
+
" <div style=\"margin-top:0.6rem;font-size:0.85rem;\">"
|
| 201 |
+
" 在当前背景色上预览文字对比度。"
|
| 202 |
+
" </div>"
|
| 203 |
+
"</div>"
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
return "".join(previews)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def _scatter_figure(result: PaletteResult) -> go.Figure:
|
| 210 |
+
"""Build a 3D scatter figure of sampled pixels in RGB space."""
|
| 211 |
+
|
| 212 |
+
fig = go.Figure()
|
| 213 |
+
|
| 214 |
+
samples = result.samples
|
| 215 |
+
labels = result.labels
|
| 216 |
+
for idx, color in enumerate(result.colors):
|
| 217 |
+
cluster_points = samples[labels == idx]
|
| 218 |
+
if cluster_points.size == 0:
|
| 219 |
+
continue
|
| 220 |
+
fig.add_trace(
|
| 221 |
+
go.Scatter3d(
|
| 222 |
+
x=cluster_points[:, 0],
|
| 223 |
+
y=cluster_points[:, 1],
|
| 224 |
+
z=cluster_points[:, 2],
|
| 225 |
+
mode="markers",
|
| 226 |
+
marker=dict(size=3, color=color.hex, opacity=0.35),
|
| 227 |
+
name=f"Cluster {idx + 1}",
|
| 228 |
+
hovertemplate="R:%{x:.0f}<br>G:%{y:.0f}<br>B:%{z:.0f}<extra>{color.hex}</extra>",
|
| 229 |
+
)
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
fig.add_trace(
|
| 233 |
+
go.Scatter3d(
|
| 234 |
+
x=result.centroids[:, 0],
|
| 235 |
+
y=result.centroids[:, 1],
|
| 236 |
+
z=result.centroids[:, 2],
|
| 237 |
+
mode="markers",
|
| 238 |
+
marker=dict(
|
| 239 |
+
size=9,
|
| 240 |
+
color=[color.hex for color in result.colors],
|
| 241 |
+
symbol="diamond",
|
| 242 |
+
line=dict(width=1.5, color="#111111"),
|
| 243 |
+
),
|
| 244 |
+
name="Centroids",
|
| 245 |
+
hovertemplate="R:%{x:.0f}<br>G:%{y:.0f}<br>B:%{z:.0f}<extra>Centroid</extra>",
|
| 246 |
+
)
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
fig.update_layout(
|
| 250 |
+
scene=dict(
|
| 251 |
+
xaxis=dict(title="Red", range=[0, 255]),
|
| 252 |
+
yaxis=dict(title="Green", range=[0, 255]),
|
| 253 |
+
zaxis=dict(title="Blue", range=[0, 255]),
|
| 254 |
+
aspectmode="cube",
|
| 255 |
+
),
|
| 256 |
+
legend=dict(orientation="h", x=0.0, y=1.02),
|
| 257 |
+
margin=dict(l=0, r=0, t=30, b=0),
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
return fig
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def analyze_image(
|
| 264 |
+
image: Image.Image | np.ndarray,
|
| 265 |
+
num_colors: int,
|
| 266 |
+
seed: int,
|
| 267 |
+
) -> Tuple[str, str, go.Figure | None, List[dict]]:
|
| 268 |
+
"""Processing function used by the Gradio interface."""
|
| 269 |
+
|
| 270 |
+
if image is None:
|
| 271 |
+
empty = "<div>请上传图片</div>"
|
| 272 |
+
return empty, empty, None, []
|
| 273 |
+
|
| 274 |
+
result = extract_palette(image, num_colors=num_colors, seed=seed)
|
| 275 |
+
|
| 276 |
+
json_payload = [
|
| 277 |
+
{
|
| 278 |
+
"hex": color.hex,
|
| 279 |
+
"rgb": color.rgb,
|
| 280 |
+
"percentage": round(color.percentage, 4),
|
| 281 |
+
}
|
| 282 |
+
for color in result.colors
|
| 283 |
+
]
|
| 284 |
+
|
| 285 |
+
return (
|
| 286 |
+
_gradient_html(result.colors),
|
| 287 |
+
_typography_html(result.colors),
|
| 288 |
+
_scatter_figure(result),
|
| 289 |
+
json_payload,
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
CUSTOM_CSS = None
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def build_demo(default_num_colors: int = 5, default_seed: int = 42) -> "gr.Blocks":
|
| 297 |
+
"""Create the Gradio Blocks interface."""
|
| 298 |
+
|
| 299 |
+
default_num_colors = int(max(2, min(12, default_num_colors)))
|
| 300 |
+
default_seed = int(max(0, min(10_000, default_seed)))
|
| 301 |
+
|
| 302 |
+
with gr.Blocks(css=CUSTOM_CSS, title="Palette Explorer") as demo:
|
| 303 |
+
gr.Markdown(
|
| 304 |
+
"""
|
| 305 |
+
# 🎨 Palette Explorer
|
| 306 |
+
|
| 307 |
+
上传图片,提取主要色调,并以多种方式查看调色板数据。
|
| 308 |
+
"""
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
with gr.Row(equal_height=True):
|
| 312 |
+
with gr.Column(scale=6, min_width=420):
|
| 313 |
+
input_image = gr.Image(label="上传图片", type="pil", height=420)
|
| 314 |
+
with gr.Row():
|
| 315 |
+
num_colors = gr.Slider(
|
| 316 |
+
minimum=2,
|
| 317 |
+
maximum=12,
|
| 318 |
+
value=default_num_colors,
|
| 319 |
+
step=1,
|
| 320 |
+
label="调色板颜色数量",
|
| 321 |
+
)
|
| 322 |
+
seed = gr.Slider(
|
| 323 |
+
minimum=0,
|
| 324 |
+
maximum=10_000,
|
| 325 |
+
value=default_seed,
|
| 326 |
+
step=1,
|
| 327 |
+
label="随机种子",
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
run_btn = gr.Button("生成调色板")
|
| 331 |
+
gr.Markdown("_提示:尝试调整颜色数量和随机种子,以探索不同的聚类结果。_")
|
| 332 |
+
|
| 333 |
+
with gr.Column(scale=6, min_width=420):
|
| 334 |
+
gradient_view = gr.HTML(label="渐变光带")
|
| 335 |
+
typography_view = gr.HTML(label="排版预览")
|
| 336 |
+
scatter_view = gr.Plot(label="RGB 三维散点")
|
| 337 |
+
data_view = gr.JSON(label="调色板数据")
|
| 338 |
+
|
| 339 |
+
run_btn.click(
|
| 340 |
+
fn=analyze_image,
|
| 341 |
+
inputs=[input_image, num_colors, seed],
|
| 342 |
+
outputs=[
|
| 343 |
+
gradient_view,
|
| 344 |
+
typography_view,
|
| 345 |
+
scatter_view,
|
| 346 |
+
data_view,
|
| 347 |
+
],
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
return demo
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def launch_demo(
|
| 354 |
+
default_num_colors: int = 5,
|
| 355 |
+
default_seed: int = 42,
|
| 356 |
+
*,
|
| 357 |
+
share: bool = False,
|
| 358 |
+
server_name: str | None = None,
|
| 359 |
+
server_port: int | None = None,
|
| 360 |
+
) -> None:
|
| 361 |
+
"""Launch the Gradio demo with optional configuration overrides."""
|
| 362 |
+
|
| 363 |
+
demo = build_demo(default_num_colors=default_num_colors, default_seed=default_seed)
|
| 364 |
+
demo.launch(share=share, server_name=server_name, server_port=server_port)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def run_cli(image: str, num_colors: int, seed: int) -> None:
|
| 369 |
+
"""Command-line execution path printing palette information."""
|
| 370 |
+
|
| 371 |
+
result = extract_palette(image, num_colors=num_colors, seed=seed)
|
| 372 |
+
|
| 373 |
+
print("Hex RGB Percentage")
|
| 374 |
+
for color in result.colors:
|
| 375 |
+
print(f"{color.hex} {color.rgb} {color.percentage * 100:.2f}%")
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def main() -> None:
|
| 380 |
+
"""Entry point that supports both CLI and UI usage."""
|
| 381 |
+
|
| 382 |
+
parser = argparse.ArgumentParser(description="Extract a color palette or launch the Gradio UI")
|
| 383 |
+
parser.add_argument("image", nargs="?", help="Path to the input image for CLI mode")
|
| 384 |
+
parser.add_argument("-n", "--num-colors", type=int, default=5, help="Number of colors in the palette or default for UI")
|
| 385 |
+
parser.add_argument("-s", "--seed", type=int, default=42, help="Random seed for k-means initialisation or default for UI")
|
| 386 |
+
parser.add_argument("--ui", action="store_true", help="Launch the Gradio interface instead of the CLI output")
|
| 387 |
+
parser.add_argument("--share", action="store_true", help="Share the Gradio demo publicly")
|
| 388 |
+
parser.add_argument("--server-name", type=str, default=None, help="Hostname for Gradio server")
|
| 389 |
+
parser.add_argument("--server-port", type=int, default=None, help="Port for Gradio server")
|
| 390 |
+
|
| 391 |
+
args = parser.parse_args()
|
| 392 |
+
|
| 393 |
+
if args.ui or args.image is None:
|
| 394 |
+
launch_demo(
|
| 395 |
+
default_num_colors=args.num_colors,
|
| 396 |
+
default_seed=args.seed,
|
| 397 |
+
share=args.share,
|
| 398 |
+
server_name=args.server_name,
|
| 399 |
+
server_port=args.server_port,
|
| 400 |
+
)
|
| 401 |
+
else:
|
| 402 |
+
run_cli(args.image, num_colors=args.num_colors, seed=args.seed)
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
if __name__ == "__main__":
|
| 406 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=4.15.0
|
| 2 |
+
plotly>=5.18.0
|
| 3 |
+
numpy>=1.24.0
|
| 4 |
+
pillow>=10.0.0
|