如何将颜色强度值映射到其名称?

时间:2019-02-25 14:18:54

标签: python image-processing

我有主色调和从图像中提取的调色板。我想映射这些强度值并打印主色和所有 调色板中的颜色。我可以使用Color_Thief轻松提取这些强度值。但是如何用名称映射它们?这是我到目前为止所做的:

enter image description here

在列表变量中,我还准备了颜色强度的值。这些是值:

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以将PILwebcolors结合使用以获取图像的颜色统计信息:

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>netcoreapp2.2</TargetFramework>
        <IsPackable>false</IsPackable>
    </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="log4net" Version="2.0.8" />
    </ItemGroup>
    <ItemGroup>
        <ProjectReference Include="..\..\vtortola.WebSockets.Deflate\vtortola.WebSockets.Deflate.csproj" />
        <ProjectReference Include="..\..\vtortola.WebSockets.Rfc6455\vtortola.WebSockets.Rfc6455.csproj" />
        <ProjectReference Include="..\..\vtortola.WebSockets\vtortola.WebSockets.csproj" />
    </ItemGroup>
    <ItemGroup>
        <Folder Include="Properties\" />
        <Folder Include="Properties\" />
    </ItemGroup>
</Project>

例如下图:

enter image description here

5种最常见的颜色是:

import webcolors
from PIL import Image
from collections import Counter

def get_colour_name(requested_colour):
    try:
        return webcolors.rgb_to_name(requested_colour)
    except ValueError:
        min_colours = {}
        for key, name_ in webcolors.css3_hex_to_names.items():
            r_c, g_c, b_c = webcolors.hex_to_rgb(key)
            rd = (r_c - requested_colour[0]) ** 2
            gd = (g_c - requested_colour[1]) ** 2
            bd = (b_c - requested_colour[2]) ** 2
            min_colours[(rd + gd + bd)] = name_
        return min_colours[min(min_colours.keys())]

image = Image.open('image.jpg')
pixels = image.load()
w, h = image.size
colors = []
for x in range(w):
    for y in range(h):
        colors.append(get_colour_name(pixels[x, y]))

for i, c in enumerate(Counter(colors).most_common(5)):
    print('{}. {:15} {:>2.1f}%'.format(i+1, c[0], c[1] * 100 / len(colors)))