A lab finished in Udacity Computer Vision Nanodegree.
K均值聚类(k-means clustering)是一种非监督学习(unsupervised learning)方法,也就是说无需使用标签数据
自行实现的k-means点此
1、Import resources and display image
import numpy as np
import matplotlib.pyplot as plt
import cv2
%matplotlib inline
# Read in the image
image = cv2.imread('images/monarch.jpg')
# Change color to RGB (from BGR)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(image)
2、Prepare data for k-means
# Reshape image into a 2D array of pixels and 3 color values (RGB)
pixel_vals = image.reshape((-1,3))
# Convert to float type
pixel_vals = np.float32(pixel_vals)
3、Implement k-means clustering
# define stopping criteria
# you can change the number of max iterations for faster convergence!
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
# Select a value for k
# then perform k-means clustering
k = 2
retval, labels, centers = cv2.kmeans(pixel_vals, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# convert data into 8-bit values
#centers = np.uint8(centers)
color = np.uint8([[255, 0, 0],
[0, 0, 255]])
segmented_data = color[labels.flatten()]
#segmented_data = centers[labels.flatten()]
# reshape data into the original image dimensions
segmented_image = segmented_data.reshape((image.shape))
plt.imshow(segmented_image)
## Visualize one segment, try to find which is the butterfly, background, etc!
labels_reshape = labels.reshape(image.shape[0], image.shape[1])
plt.imshow(labels_reshape==0, cmap='gray')
# mask an image segment by cluster
cluster = 0 # the first cluster
masked_image = np.copy(image)
# turn the mask yellow!
masked_image[labels_reshape == cluster] = [255, 255, 0]
plt.imshow(masked_image)