如何将RGB或HEX颜色代码分组为更大的颜色组? [英] How to group RGB or HEX color codes to bigger sets of color groups?

查看:13
本文介绍了如何将RGB或HEX颜色代码分组为更大的颜色组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在分析大量图像并提取主色码。

我要将它们分组为通用颜色名称范围,如绿色、深绿色、浅绿色、蓝色、深蓝、浅蓝色等。

我正在寻找一种语言不可知的方式,以便自己实现一些东西,如果有我可以研究的例子来实现这一点,我将非常感激。

推荐答案

@saastn的精彩答案假设您有一组要对图像进行排序的预定义颜色。如果您只想将图像分类为某组X个等距颜色中的一种颜色(如直方图),则实现起来会更容易。

总而言之,将图像中每个像素的颜色四舍五入为某组等距颜色箱中最接近的颜色。这会将颜色的精度降低到您想要的任何颜色数量。然后计算图像中的所有颜色,并选择最常用的颜色作为该图像的分类。

以下是我在Python中的实现:

import cv2
import numpy as np

#Set this to the number of colors that you want to classify the images to
number_of_colors = 8

#Verify that the number of colors chosen is between the minimum possible and maximum possible for an RGB image.
assert 8 <= number_of_colors <= 16777216

#Get the cube root of the number of colors to determine how many bins to split each channel into.
number_of_values_per_channel = number_of_colors ** ( 1 / 3 )

#We will divide each pixel by its maximum value divided by the number of bins we want to divide the values into (minus one for the zero bin).
divisor = 255 / (number_of_values_per_channel - 1)

#load the image and convert it to float32 for greater precision. cv2 loads the image in BGR (as opposed to RGB) format.
image = cv2.imread("image.png", cv2.IMREAD_COLOR).astype(np.float32)

#Divide each pixel by the divisor defined above, round to the nearest bin, then convert float32 back to uint8.
image = np.round(image / divisor).astype(np.uint8)

#Flatten the columns and rows into just one column per channel so that it will be easier to compare the columns across the channels.
image = image.reshape(-1, image.shape[2])

#Find and count matching rows (pixels), where each row consists of three values spread across three channels (Blue column, Red column, Green column).
uniques = np.unique(image, axis=0, return_counts=True)

#The first of the two arrays returned by np.unique is an array compromising all of the unique colors.
colors = uniques[0]

#The second of the two arrays returend by np.unique is an array compromising the counts of all of the unique colors.
color_counts = uniques[1]

#Get the index of the color with the greatest frequency
most_common_color_index = np.argmax(color_counts)

#Get the color that was the most common
most_common_color = colors[most_common_color_index]

#Multiply the channel values by the divisor to return the values to a range between 0 and 255
most_common_color = most_common_color * divisor

#If you want to name each color, you could also provide a list sorted from lowest to highest BGR values comprising of
#the name of each possible color, and then use most_common_color_index to retrieve the name.
print(most_common_color)

这篇关于如何将RGB或HEX颜色代码分组为更大的颜色组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆