获取图像中像素的主要颜色

时间:2021-02-18 21:59:13

标签: python opencv colors color-detection

我正在尝试获取我的图像的所有颜色。我用

unique_rgbs = np.unique(resized_img.reshape(-1, resized_img.shape[2]), axis=0)

我的期望是得到 6 种颜色,但我得到了大约 2000 种颜色,因为颜色之间的边界不是实心的。然后我更改了图像的颜色,使其只有红色 [255,0,0] 绿色 [0,255,0] 蓝色 [255,0,0] 和黄色 [0,255,255],并试图摆脱使用以下代码的所有其他颜色

img[img[...,0] > 128] = 255
img[img[...,0] <= 128] = 0
 
img[img[...,1] > 128] = 255
img[img[...,1] <= 128] = 0
 
img[img[...,2] > 128] = 255
img[img[...,2] <= 128] = 0

但它不起作用。结果图像只有黑白,np.unique 的结果表明图像中有 26 种颜色。

original image

zoomed in detail

1 个答案:

答案 0 :(得分:1)

聚类似乎在这种情况下有效:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

X = plt.imread("xGmSz.jpg").reshape(-1, 3)

# cluster pixels
N = 6
km = KMeans(n_clusters=N, init="k-means++")
km.fit(X)
# get cluster centers
colors = km.cluster_centers_.astype(int)
plt.imshow(cen.reshape(1, N, 3))

它给出:

enter image description here