SALE! Use code blackfriday for 40% off everything!
Hurry, sale ends soon! Click to see the full catalog.

K-Means Clustering for Image Classification Using OpenCV

In a previous tutorial, we have explored the use of 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. 

We have, so far, seen how to apply the k-means clustering algorithm to a simple two-dimensional dataset containing distinct clusters, as well as to the problem of image color quantization. 

In this tutorial, you are going to learn how to apply OpenCV’s k-means clustering algorithm for the task of image classification. 

After completing this tutorial, you will know:

  • Why k-means clustering can be applied to image classification. 
  • How to apply 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. 

Let’s get started. 

K-Means Clustering for Image Classification Using OpenCV
Photo by Jeremy Thomas, some rights reserved.

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 the automatic grouping of 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. Its aim is 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 with the aim of labelling 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 task of image classification. 

For such a task, we will be employing the OpenCV digits dataset introduced in a previous tutorial, where our aim will be to try to group together images of similar handwritten digits in an unsupervised manner (i.e. without making any use of 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, organised 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$\times$400, which means that we’ll first need to reshape it back to 20$\times$20 pixel images before proceeding to visual them:

The representative images of the cluster centers are as follows:

Representative Images of the Cluster Centers Found by the k-Means Algorithm

It is remarkable to find that the cluster centers generated by the k-means algorithm indeed resemble the handwritten digits that are 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, of course, due to the fact that, while the k-means algorithm can cluster similar data together, it has no notion of its order. However, it also creates a problem when it comes to comparing the predicted labels with the ground truth ones. This is because, while the ground truth labels have been generated to correspond to the digit numbers featured inside the images, the cluster labels generated by the k-means algorithm do not necessarily follow the same convention. In order 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 of which digits have been mistaken for one another:

The confusion matrix needs to be interpreted as follows:

Interpreting the Confusion Matrix

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 of the other digits, mostly with 1. We may also see that 7 has been mostly mistaken with 9, while 8 has been mostly mistaken with 3. 

These results do not necessarily come as a surprise because, if we had to have a look at the digits in the dataset, we may see that the curves and skew of several different digits cause them to resemble each other. For the purpose of investigating 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:

Representative Images of the Cluster Centers Found by the k-Means Algorithm

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 that you may introduce to improve the accuracy?

Further Reading

This section provides more resources on the topic if you are looking to go deeper.

Books

Websites

Summary

In this tutorial, you learned how to apply OpenCV’s k-means clustering algorithm for the task of image classification.

Specifically, you learned:

  • Why k-means clustering can be applied to image classification. 
  • How to apply 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.

, , ,

2 Responses to K-Means Clustering for Image Classification Using OpenCV

  1. Avatar
    shincheng November 1, 2023 at 5:56 pm #

    For such a task, we will be employing the OpenCV digits dataset introduced in a “previous tutorial”

    The link embedded within ‘previous tutorial’ is invalid.

    • Avatar
      James Carmichael November 2, 2023 at 10:46 am #

      Thank you for your feedback shincheng!

Leave a Reply