Horje
k-means clustering and disabling clusters Code Example
k-means clustering and disabling clusters
img = path
img = cv2.imread(img)
img = cv2.cvtColor(img,cv2.COLOR_BGR2LAB)
pixVal = img.reshape((-1,3))
pixVal = np.float(pixVal)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2)
# number of clusters (K)
k = 3
_, labels, (centers) = cv2.kmeans(pixVal, k, None,
                                  criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# convert back to 8 bit values
centers = np.uint8(centers)

# flatten the labels array
labels = labels.flatten()

# convert all pixels to the color of the centroids
segmented_image = centers[labels.flatten()]
# reshape back to the original image dimension
segmented_image = segmented_image.reshape(image.shape)
# show the image
plt.imshow(segmented_image)
plt.show()

# disable only the cluster number 2 (turn the pixel into black)
masked_image = np.copy(image)
# convert to the shape of a vector of pixel values
masked_image = masked_image.reshape((-1, 3))
# color (i.e cluster) to disable
cluster = 2
masked_image[labels == cluster] = [0, 0, 0]
# convert back to original shape
masked_image = masked_image.reshape(image.shape)
# show the image
plt.imshow(masked_image)
plt.show()




Python

Related
numpy prod Code Example numpy prod Code Example
create loading in pyqt Code Example create loading in pyqt Code Example
pandas mean and sum Code Example pandas mean and sum Code Example
date component Code Example date component Code Example
urllib2 py Code Example urllib2 py Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
10