2025-08-21 17:35:09 +08:00
|
|
|
|
from PIL import Image
|
|
|
|
|
import colorsys
|
|
|
|
|
|
|
|
|
|
def get_unique_colors(image_path):
|
|
|
|
|
img = Image.open(image_path).convert("RGB")
|
|
|
|
|
unique_colors = list(set(img.getdata()))
|
|
|
|
|
return unique_colors
|
|
|
|
|
|
|
|
|
|
def get_representative_colors(colors, n=12):
|
|
|
|
|
# 按亮度排序并均匀抽取
|
|
|
|
|
def brightness(rgb):
|
|
|
|
|
r, g, b = rgb
|
|
|
|
|
return 0.2126*r + 0.7152*g + 0.0722*b
|
|
|
|
|
|
|
|
|
|
colors.sort(key=brightness)
|
|
|
|
|
total = len(colors)
|
|
|
|
|
if total <= n:
|
|
|
|
|
return colors
|
|
|
|
|
step = total / n
|
|
|
|
|
return [colors[int(i*step)] for i in range(n)]
|
|
|
|
|
|
|
|
|
|
def sort_colors_by_hue(colors):
|
|
|
|
|
# 转为 HSV,并按色相排序
|
|
|
|
|
def rgb_to_hue(rgb):
|
|
|
|
|
r, g, b = [x/255.0 for x in rgb]
|
|
|
|
|
h, s, v = colorsys.rgb_to_hsv(r, g, b)
|
|
|
|
|
return h
|
|
|
|
|
return sorted(colors, key=rgb_to_hue)
|
|
|
|
|
|
|
|
|
|
def show_color_preview(colors, width=600, height_per_color=50):
|
|
|
|
|
n = len(colors)
|
|
|
|
|
height = n * height_per_color
|
|
|
|
|
img = Image.new("RGB", (width, height))
|
|
|
|
|
|
|
|
|
|
for i, color in enumerate(colors):
|
|
|
|
|
for y in range(i*height_per_color, (i+1)*height_per_color):
|
|
|
|
|
for x in range(width):
|
|
|
|
|
img.putpixel((x, y), color)
|
|
|
|
|
|
|
|
|
|
img.show()
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
image_path = r"D:\项目资料\技术文档资料\中康项目资料\11.png"
|
|
|
|
|
|
|
|
|
|
colors = get_unique_colors(image_path)
|
|
|
|
|
rep_colors = get_representative_colors(colors, 12)
|
|
|
|
|
sorted_colors = sort_colors_by_hue(rep_colors)
|
|
|
|
|
|
|
|
|
|
print("12 个代表性颜色(按彩虹顺序):")
|
|
|
|
|
for i, color in enumerate(sorted_colors, 1):
|
|
|
|
|
print(f"{i}: {color}")
|
|
|
|
|
|
|
|
|
|
show_color_preview(sorted_colors)
|