In a previous tutorial, we explored using the k-means clustering algorithm as an unsupervised machine learning technique that seeks to group similar data into distinct clusters to uncover patterns in the data.
So far, we have seen how to apply the k-means clustering algorithm to a simple two-dimensional dataset containing distinct clusters and the problem of image color quantization.
In this tutorial, you will learn how to apply OpenCV’s k-means clustering algorithm for image classification.
After completing this tutorial, you will know:
- Why k-means clustering can be applied to image classification.
- Applying the k-means clustering algorithm to the digit dataset in OpenCV for image classification.
- How to reduce the digit variations due to skew to improve the accuracy of the k-means clustering algorithm for image classification.
Kick-start your project with my book Machine Learning in OpenCV. It provides self-study tutorials with working code.
Let’s get started.
Tutorial Overview
This tutorial is divided into two parts; they are:
- Recap of k-Means Clustering as an Unsupervised Machine Learning Technique
- Applying k-Means Clustering to Image Classification
Recap of k-Means Clustering as an Unsupervised Machine Learning Technique
In a previous tutorial, we have been introduced to k-means clustering as an unsupervised learning technique.
We have seen that this technique involves automatically grouping data into distinct groups (or clusters), where the data within each cluster are similar to one another but different from those in the other clusters. It aims to uncover patterns in the data that may not be apparent before clustering.
We have applied the k-means clustering algorithm to a simple two-dimensional dataset containing five clusters to label the data points belonging to each cluster accordingly, and subsequently to the task of color quantization where we have used this algorithm to reduce the number of distinct colors representing an image.
In this tutorial, we shall again exploit the strength of k-means clustering in uncovering hidden structures in the data by applying it to the image classification task.
For such a task, we will be employing the OpenCV digits dataset introduced in a previous tutorial, where we will aim to try to group images of similar handwritten digits in an unsupervised manner (i.e., without using the ground truth label information).
Applying k-Means Clustering to Image Classification
We’ll first need to load the OpenCV digits image, divide it into its many sub-images that feature handwritten digits from 0 to 9, and create their corresponding ground truth labels that will enable us to quantify the performance of the k-means clustering algorithm later on:
The returned imgs array contains 5,000 sub-images, organized row-wise in the form of flattened one-dimensional vectors, each comprising 400 pixels:
The k-means algorithm can subsequently be provided with input arguments that are equivalent to those that we have used for our color quantization example, with the only exception being that we’ll need to pass the imgs array as the input data, and that we shall be setting the value of K clusters to 10 (i.e., the number of digits that we have available):
The kmeans function returns a centers array, which should contain a representative image for each cluster. The returned centers array is of shape 10
The representative images of the cluster centers are as follows:
It is remarkable that the cluster centers generated by the k-means algorithm indeed resemble the handwritten digits contained in the OpenCV digits dataset.
You may also notice that the order of the cluster centers does not necessarily follow the order of the digits from 0 to 9. This is because the k-means algorithm can cluster similar data together but has no notion of its order. However, it also creates a problem when comparing the predicted labels with the ground truth ones. This is because the ground truth labels have been generated to correspond to the digit numbers featured inside the images. However, the cluster labels generated by the k-means algorithm do not necessarily follow the same convention. To solve this problem, we need to re-order the cluster labels:
Now we’re ready to calculate the accuracy of the algorithm, by finding the percentage of predicted labels that correspond to the ground truth:
The complete code listing up to this point is as follows:
Now, let’s print out the confusion matrix to gain a deeper insight into which digits have been mistaken for one another:
The confusion matrix needs to be interpreted as follows:
The values on the diagonal indicate the number of correctly predicted digits, whereas the off-diagonal values indicate the misclassifications per digit. We may see that the best performing digit is 0, with the highest diagonal value and very few misclassifications. The worst performing digit is 9 since this has the highest number of misclassifications with many other digits, mostly with 4. We may also see that 7 has been mostly mistaken with 4, while 8 has been mostly mistaken with 3.
These results do not necessarily come as a surprise because, if we had to look at the digits in the dataset, we might see that the curves and skew of several different digits cause them to resemble each other. To investigate the effect of reducing the digit variations, let’s introduce a function, deskew_image(), that applies an affine transformation to an image based on a measure of skew calculated from the image moments:
The de-skewing function has the following effect on some of the digits:

The First Column Depicts the Original Dataset Images, While the Second Column Shows Images Corrected for Skew
Remarkably, the accuracy rises to 70.92% when the skew of the digits is reduced, while the cluster centers become more representative of the digits in the dataset:
This result shows that skew was a highly contributing factor to the loss of accuracy that we experienced without its correction.
Can you think of any other pre-processing steps you may introduce to improve the accuracy?
Further Reading
This section provides more resources on the topic if you want to go deeper.
Books
Websites
- 10 Clustering Algorithms With Python, https://machinelearningmastery.com/clustering-algorithms-with-python/
- K-Means Clustering in OpenCV, https://docs.opencv.org/3.4/d1/d5c/tutorial_py_kmeans_opencv.html
- k-means clustering, https://en.wikipedia.org/wiki/K-means_clustering
Summary
In this tutorial, you learned how to apply OpenCV’s k-means clustering algorithm for image classification.
Specifically, you learned:
- Why k-means clustering can be applied to image classification.
- Applying the k-means clustering algorithm to the digit dataset in OpenCV for image classification.
- How to reduce the digit variations due to skew to improve the accuracy of the k-means clustering algorithm for image classification.
Do you have any questions?
Ask your questions in the comments below, and I will do my best to answer.




No comments:
Post a Comment