...

Python Image Segmentation Made Easy with OpenCV and K-means Algorithm

OpenCV Image Segmentation with K-Means in Pytho

Introduction

K-Means image segmentation is a simple and effective way to partition an image into meaningful color regions.
This tutorial shows how to implement K-Means segmentation in Python using OpenCV.


You will learn how to reshape image pixels, cluster them into K groups, and rebuild a segmented image from cluster centroids.


This approach is great for color quantization, background simplification, and fast, unsupervised segmentation.
We will keep the code compact and explain every command for clarity and SEO-friendly learning.

Check the video tutorial here : https://www.youtube.com/watch?v=a2Kti9UGtrU

You can find more similar tutorials in my blog posts page here : https://eranfeit.net/blog/

K-Means Segmentation in OpenCV with Python

This section walks you through loading an image, reshaping pixels, configuring K-Means criteria, clustering, and reconstructing the segmented output.
The code block contains short explanations directly above each Python command for copy-paste convenience.

### Import OpenCV for image processing and NumPy for array manipulation. import cv2 import numpy as np  ### Read the input image from disk using OpenCV's imread function. ### The image path should point to a valid file on your system. img = cv2.imread("Open-CV/Image-Segmentation-Using-K-means/beach-and-boats.jpeg")  ### Print the original image shape to understand height, width, and channel count. print(img.shape)  ### Reshape the image to a 2D array where each row is a pixel and columns are color channels. ### This converts (H, W, 3) into (H*W, 3) for K-Means input. twoDim = img.reshape((-1,3)) print(twoDim.shape)  ### Convert the reshaped pixel array to 32-bit float as required by cv2.kmeans. twoDim = np.float32(twoDim)  ### Define the termination criteria for K-Means: either a small epsilon change or a max number of iterations. ### TERM_CRITERIA_EPS stops when the specified accuracy is reached. ### TERM_CRITERIA_MAX_ITER stops when the iteration limit is reached. criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER , 10 , 1.0)  ### Choose the number of clusters K to control how many color segments you want. ### Higher K yields more detailed segmentation, lower K yields simpler regions. K=3  ### Set the number of attempts to run K-Means with different initial labels. ### The best solution (lowest compactness) across attempts is returned. attamps = 10  ### Run OpenCV's K-Means on the pixel data to obtain cluster centers and labels for each pixel. ### KMEANS_PP_CENTERS uses K-Means++ initialization for better centroid seeds. ret , label , center = cv2.kmeans(twoDim, K, None , criteria , attamps, cv2.KMEANS_PP_CENTERS)  ### Convert the cluster centers back to 8-bit integers to map them to an image. center = np.uint8(center)  ### Replace each pixel by the centroid color of its assigned cluster for a segmented look. res = center[label.flatten()]  ### Reshape the flat result back to the original image dimensions. result_image = res.reshape((img.shape))  ### Display the segmented result in a window titled "result_image". cv2.imshow("result_image",result_image)  ### Save the segmented image to disk for later use or sharing. cv2.imwrite("c:/temp/result3-100.jpg",result_image)  ### Optionally display the original image for visual comparison. cv2.imshow("img",img)  ### Wait for a key press so the windows remain visible until you close them. cv2.waitKey(0)  ### Clean up any OpenCV windows that were opened during display. cv2.destroyAllWindows() 

You can find the full code here : https://ko-fi.com/s/c7e8e45f56

You read an image, convert pixels to a 2D float array, and run K-Means with K clusters and stopping criteria.
You then rebuild an image by mapping each pixel to its cluster centroid, display the result, and save the output to disk.

Image Segmentation with cv2 Kmeans (OpenCV, Python)

If you’re looking for a fast, unsupervised way to separate foreground from background or reduce colors before training a model, cv2 kmeans is a powerful baseline.

Using cv2.kmeans you cluster pixel features (commonly RGB values reshaped to (-1, 3) and cast to np.float32) into K groups, then rebuild the image from the cluster centers to get a clean, quantized result that highlights dominant regions. Typical settings include a convergence criteria like cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, a small number of attempts (e.g., 10), and cv2.KMEANS_PP_CENTERS for stable initialization.

In practice, start with K=2–5 for quick image segmentation, color quantization, or pre-processing to boost downstream tasks (edge detection, contour extraction, or preparing masks for labeling). Because cv2 kmeans runs directly in OpenCV, it’s lightweight, easy to tune, and ideal for tutorials and production scripts where you want reproducible clustering without heavy dependencies.


Connect :

☕ Buy me a coffee — https://ko-fi.com/eranfeit

🖥️ Email : feitgemel@gmail.com

🌐 https://eranfeit.net

🤝 Fiverr : https://www.fiverr.com/s/mB3Pbb

Enjoy,

Eran

error: Content is protected !!
Eran Feit