Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Clustering images

Clustering images

Mahmood Amintoosi, Fall 2026

Computer Science Dept, Ferdowsi University of Mashhad

Source
• First, it reads all jpg images from a given folder and converts them into NumPy arrays.

• Then it computes the mean pixel intensity of each image and builds a three-dimensional vector from them.

• Then it uses the k-means algorithm from scikit-learn to cluster the mean vectors. You can set the number of clusters as you like.

• Finally, it displays the images of each cluster using matplotlib.

(120, 160, 3)
<Figure size 500x300 with 9 Axes>
(9, 3)
/usr/local/lib/python3.10/dist-packages/sklearn/cluster/_kmeans.py:870: FutureWarning: The default value of `n_init` will change from 10 to 'auto' in 1.4. Set the value of `n_init` explicitly to suppress the warning
  warnings.warn(
<Figure size 600x300 with 4 Axes>
<Figure size 600x300 with 3 Axes>
<Figure size 600x300 with 2 Axes>

Image clustering in high-dimensional space

(3,)
(120, 160, 3)
(100, 100, 3)
(10000, 3)
[0.56470588 0.67689584 0.38695552]
[0.56470588 0.67689584 0.38695552]
(30000,)
[0.56470588 0.67689584 0.38695552]
[0.56470588 0.67689584 0.38695552]
(9, 30000)
/usr/local/lib/python3.10/dist-packages/sklearn/cluster/_kmeans.py:870: FutureWarning: The default value of `n_init` will change from 10 to 'auto' in 1.4. Set the value of `n_init` explicitly to suppress the warning
  warnings.warn(
<Figure size 600x300 with 3 Axes>
<Figure size 600x300 with 3 Axes>
<Figure size 600x300 with 3 Axes>