from skimage.io import imreadfrom skimage.color import rgb2grayimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlinefrom scipy import ndimage# Scaling the image pixels values within 0-1img = imread('./apple-orange.jpg') / 255plt.imshow(img)plt.title('Original')plt.show()
由于肉眼可见,图像中有五个色段
苹果的绿色部分
橙子的橙色部分
苹果和橙子底部的灰色阴影
苹果顶部和右侧部分的亮黄色部分
白色背景
让我们看看我们是否可以使用来自 scikit-learn 的 K 均值算法对它们进行聚类
# For clustering the image using k-means, we first need to convert it into a 2-dimensional arrayimage_2D = img.reshape(img.shape[0]*img.shape[1], img.shape[2])# Use KMeans clustering algorithm from sklearn.cluster to cluster pixels in imagefrom sklearn.cluster import KMeans# tweak the cluster size and see what happens to the Outputkmeans = KMeans(n_clusters=5, random_state=0).fit(image_2D)clustered = kmeans.cluster_centers_[kmeans.labels_]# Reshape back the image from 2D to 3D imageclustered_3D = clustered.reshape(img.shape[0], img.shape[1], img.shape[2])plt.imshow(clustered_3D)plt.title('Clustered Image')plt.show()