从K-means Numpy阵列计算集群中心的凸壳

时间:2017-10-01 04:12:31

标签: python scipy k-means data-science convex-hull

我在图像上使用K-means量化时会返回Numpy颜色数组。使用K-means后,我需要取这些中心并计算一组色心的凸包。

基本上我需要找到哪些点/颜色与另一种颜色没有足够的对比度。我认为这个问题的答案是找到船体内的点(单片?),这些点不是船体的顶点。

import matplotlib.pyplot as plt
import numpy as np
from PIL import Image   
from scipy.spatial import ConvexHull
from skimage import color, exposure
from sklearn import cluster

def quantize(pixels, n_colors):
    width, height, depth = pixels.shape
    reshaped_pixels = np.reshape(pixels, (width * height, depth))
    model = cluster.KMeans(n_clusters=n_colors, n_init=100, precompute_distances=True)
    labels = model.fit_predict(reshaped_pixels)
    centers = model.cluster_centers_
    quantized_pixels = np.reshape(centers[labels], (width, height, centers.shape[1]))

    return quantized_pixels, centers, labels

def scale_image(img, max_width=100):
    img_width, img_height = img.size
    ratio = (max_width / float(img_width))
    new_height = int((float(img_height)*float(ratio)))
    img.thumbnail((max_width, new_height), Image.NEAREST)
    return img

# Open image, convert to RGB just in case
img = Image.open('image2.jpg').convert('RGB')

# Scale image to speed up processing
img = scale_image(img, 80)

# Convert to numpy array
np_img_array = np.array(img)

# Convert rgb to lab colorspace
lab_pixels = color.rgb2lab(np_img_array)

# Kmeans quantization
quantized_lab_pixels, centers, labels = quantize(lab_pixels, 16)

# Convert pixels back to rgb
quantized_rgb_pixels = (color.lab2rgb(quantized_lab_pixels)*255).astype('uint8')

# Attempt to use convex hull around cluster centers
hull = ConvexHull(centers)

for simplex in hull.simplices:
    plt.plot(centers[simplex, 0], centers[simplex, 1])
plt.scatter(*centers.T, alpha=.5, color='k', marker='v')


for p in centers:
    point_is_in_hull = point_in_hull(p, hull)
    marker = 'x' if point_is_in_hull else 'd'
    color = 'g' if point_is_in_hull else 'm'
    plt.scatter(p[0], p[1], marker=marker, color=color)

plt.show()

更新:这是我渲染的绘图输出。我没有在此渲染的绘图中使用颜色标签。

enter image description here

以下是更有帮助的内容。然而,这些图不是我需要的......我需要找出哪个聚类中心(颜色)组成船体的顶点,然后将它们配对回顶点标签。

enter image description here

这是输出的RGB颜色的示例(在左侧),然后在右侧,您将获得最终颜色,这将排除在该区域之外的聚类中心。

enter image description here

0 个答案:

没有答案