Analytics Vidhya
Published in

Analytics Vidhya

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.

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)
Original Image
# 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()
Dominant Colors

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.

--

--

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store