获取图像中像素的主颜色

2024-06-01 06:26:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图得到我的图像的所有颜色。我和你一起做

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

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

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


Tags: 图像img颜色np蓝色边界uniqueshape
1条回答
网友
1楼 · 发布于 2024-06-01 06:26:55

在这种情况下,集群似乎有效:

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

相关问题 更多 >