Image Segmentation Using K-Means
classification of an image into different groups
Image segmentation is a process of partitioning an image into multiple segments. The main motive behind this is to change the representation of image to more informative or we can focus on only those regions which are important.
Applications
It is used in medical imaging, automatic cars, object detection, video surveillance and many more.
Prerequisite is to learn K-Means Algorithm
Lets see first detect most dominating colours :
img = cv2.imread(‘./elephant.jpg’)
plt.imshow(im)
# Flattening image into 1-d array.
all_pixels = img.reshape((-1,3))
print(all_pixels.shape)dominant_colors = 4
km = KMeans(k=dominant_colors,max_iter=30)
km.fit(all_pixels)c=[]
for i in range(km.k):
c.append(km.clusters[i]['center'])# We are going to make 1 X 4 subplot each having a single color
i=1
plt.figure(0,figsize=(4,2))colors = []
for each_col in c:
plt.subplot(1,4,i)
plt.axis("off")
i+=1
colors.append(each_col)
# Color Switch
a = np.zeros((100,100,3),dtype='uint8')
a[:,:,:] = each_col
plt.imshow(a)
plt.show()
After this you will be able to see dominant colors!!
for i in range(new_image.shape[0]):
l = int(km.label[i])
new_image[i] = colors[l]
new_image = new_image.reshape((original_shape))
plt.axis(“off”)
plt.imshow(new_image)
plt.show()
We are plotting only dominant which is image segmentation.
Thanks for reading.