Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Color quantization in an image using K-means in OpenCV Python?
Color quantization reduces the number of colors in an image by grouping similar colors together. This technique helps reduce memory usage and is essential for devices with limited color display capabilities. OpenCV provides cv2.kmeans() to perform K-means clustering for efficient color quantization.
How Color Quantization Works
K-means clustering groups pixels with similar colors into K clusters. Each cluster's centroid becomes the representative color for all pixels in that cluster, effectively reducing the total number of colors to K.
Steps for Implementation
To implement color quantization using K-means clustering, follow these steps:
Import required libraries OpenCV, NumPy, and Matplotlib
Read the input image using
cv2.imread()and reshape it to an array of M×3 size (M is total pixels)Convert the image data type to
np.float32for K-means processingDefine termination criteria, number of clusters (K), and apply
cv2.kmeans()Convert results back to
uint8and reconstruct the quantized imageDisplay the resulting image with reduced colors
Example 1: Basic Color Quantization (K=8)
This example demonstrates color quantization with 8 clusters ?
import numpy as np
import cv2
# Create a sample image for demonstration
img = np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)
# Reshape image to array of pixels
z = img.reshape((-1, 3))
# Convert to np.float32
z = np.float32(z)
# Define criteria and parameters
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 8
# Apply K-means clustering
ret, label, center = cv2.kmeans(z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# Convert back to uint8 and reconstruct image
center = np.uint8(center)
quantized_data = center[label.flatten()]
quantized_image = quantized_data.reshape(img.shape)
print("Original image shape:", img.shape)
print("Number of clusters (colors):", K)
print("Quantized image shape:", quantized_image.shape)
Example 2: Comparing Different K Values
This example shows how different K values affect the quantization result ?
import numpy as np
import cv2
import matplotlib.pyplot as plt
# Create sample image
img = np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)
Z = img.reshape((-1, 3))
Z = np.float32(Z)
# Define criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
def color_quantization(Z, K, criteria, original_shape):
ret, label, center = cv2.kmeans(Z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
center = np.uint8(center)
quantized_data = center[label.flatten()]
quantized_image = quantized_data.reshape(original_shape)
return quantized_image
# Apply quantization with different K values
result_k2 = color_quantization(Z, 2, criteria, img.shape)
result_k4 = color_quantization(Z, 4, criteria, img.shape)
result_k8 = color_quantization(Z, 8, criteria, img.shape)
# Display results
plt.figure(figsize=(12, 8))
plt.subplot(2, 2, 1)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.title('Original Image')
plt.axis('off')
plt.subplot(2, 2, 2)
plt.imshow(cv2.cvtColor(result_k2, cv2.COLOR_BGR2RGB))
plt.title('K=2')
plt.axis('off')
plt.subplot(2, 2, 3)
plt.imshow(cv2.cvtColor(result_k4, cv2.COLOR_BGR2RGB))
plt.title('K=4')
plt.axis('off')
plt.subplot(2, 2, 4)
plt.imshow(cv2.cvtColor(result_k8, cv2.COLOR_BGR2RGB))
plt.title('K=8')
plt.axis('off')
plt.tight_layout()
plt.show()
Key Parameters
| Parameter | Description | Common Values |
|---|---|---|
K |
Number of clusters/colors | 2, 4, 8, 16 |
criteria |
Termination conditions | EPS + MAX_ITER |
attempts |
Number of algorithm runs | 10 |
flags |
Center initialization method | RANDOM_CENTERS, PP_CENTERS |
Effects of Different K Values
K=2: Creates a posterized effect with only 2 dominant colors
K=4: Provides basic color reduction while maintaining some detail
K=8: Offers good balance between compression and visual quality
Higher K: Preserves more original colors but reduces compression benefit
Conclusion
Color quantization using K-means clustering effectively reduces image colors while preserving visual quality. Lower K values create artistic posterized effects, while higher K values maintain more detail. Choose K based on your specific requirements for compression and visual fidelity.
