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

English · فارسی

Clustering images

Computer Science Dept, Ferdowsi University of Mashhad

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>

Exercises

  1. Cluster the pixels of an image in RGB space with K=4K=4 and display the result as an image. Explain why the region boundaries follow colour and not position.

  2. Append the coordinates (x,y)(x,y) to the colour features with a weight ww, sweep w∈{0,0.1,1,10}w\in\{0,0.1,1,10\} and describe the trade-off between colour fidelity and spatial coherence.

  3. Compute the size of the feature matrix for a 512×512512\times512 RGB image and estimate the cost of one k-means iteration with K=8K=8. How does hierarchical clustering compare?