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

问题描述

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

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

我的期望是得到 6 种颜色,但我得到了大约 2000 种颜色,因为颜色之间的边界不是实心的。然后我更改了图像的颜色,使其只有红色 [255,0] 绿色 [0,255,0] 蓝色 [255,0] 和黄色 [0,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

解决方法

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...