Coursera Machine Learning Challenges in Python: ex7-1 (Image compression with K-means clustering)

A series that implements Coursera's Machine Learning Matlab / Octave programming tasks in Python. This time we will do the first task of unsupervised learning, K-means clustering.

Introduction: Contents of the assignment

The original image (.png) has 256 gradations for each of RGB and has 16.77 million colors. The challenge is to classify this color information into 16 clusters by K-means clustering and create a 16-color image.

Install PIL library

A library called pillow is used for image processing, so install it. pip install pillow

The pillow documentation is here [http://pillow.readthedocs.org/en/3.0.x/).

First code: Import library

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

Load the image first

Use PIL.Image.open () to load the image data and load it into a 128 x 128 x 3 3D numpy array. This is reshaped (128 * 128, 3) and flattened into a 16384 x 3 2D matrix that can be passed to clustering.

img = np.array(Image.open('bird_small.png')) #img is a 128x128x3 3D matrix
img_flat = img.reshape(128*128,3)/255 #Convert to a 16384x3 2D matrix

Perform clustering

Clustering can be done in one shot KMeans.fit (data). The KMeans parameter specifies n_clusters = 16 to divide into 16 clusters.

model = KMeans(n_clusters=16).fit(img_flat)

View results

As a result of clustering, which cluster each pixel was classified into is stored in model.labels_ (number 0-15), and the value of the center of gravity of each cluster is stored in model.cluster_centers_ (16x3 matrix). You can use this to create a matrix with the value of each pixel replaced by the centroid of the cluster as model.cluster_centers_ [model.labels_] (16384 x 3 2D matrix). Reshape (128, 128, 3) to return this to a 128 x 128 x 3 3D matrix that can be displayed in the image.

img_comp = model.cluster_centers_[model.labels_].reshape(128,128,3)
plt.imshow(img_comp)

Click here for the original image and the resulting image. You can see that it has been reduced to 16 colors.

ex7-1.png ex7-2.png

All chords

The full code is here. It's short.

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

img = np.array(Image.open('bird_small.png')) #img is a 128x128x3 3D matrix
img_flat = img.reshape(128*128,3)/255 #Convert to a 16384x3 2D matrix

model = KMeans(n_clusters=16).fit(img_flat)
img_comp = model.cluster_centers_[model.labels_].reshape(128,128,3)
plt.imshow(img_comp)

in conclusion

When I was a student studying image processing 10 years ago, I implemented K-means clustering in C ++ by scratch, but it seems that it was a program with hundreds of lines ... It's a good time with the library in place.

Recommended Posts

Coursera Machine Learning Challenges in Python: ex7-1 (Image compression with K-means clustering)
Coursera Machine Learning Challenges in Python: ex2 (Logistic Regression)
Coursera Machine Learning Challenges in Python: ex1 (Linear Regression)
Coursera Machine Learning Challenges in Python: ex3 (Handwritten Number Recognition with Logistic Regression)
Coursera Machine Learning Challenges in Python: ex7-2 (Principal Component Analysis)
Coursera Machine Learning Challenges in Python: ex5 (Adjustment of Regularization Parameters)
Coursera Machine Learning Challenges in Python: ex6 (How to Adjust SVM Parameters)
I started machine learning with Python Clustering & Dimension Compression & Visualization
Machine learning with Python! Preparation
Tweet with image in Python
Beginning with Python machine learning
Machine learning with python (1) Overall classification
Python: Preprocessing in Machine Learning: Overview
"Scraping & machine learning with Python" Learning memo
Amplify images for machine learning with python
Machine learning with python (2) Simple regression analysis
[python] Frequently used techniques in machine learning
Python: Preprocessing in machine learning: Data acquisition
[Shakyo] Encounter with Python for machine learning
Easy image processing in Python with Pillow
[Python] Saving learning results (models) in machine learning
Python: Preprocessing in machine learning: Data conversion
Build AI / machine learning environment with Python
[Python] Easy introduction to machine learning with python (SVM)
Machine learning starting with Python Personal memorandum Part2
Machine learning starting with Python Personal memorandum Part1
Extract the color of the object in the image with Mask R-CNN and K-Means clustering
[Python] Collect images with Icrawler for machine learning [1000 images]
Create an image with characters in python (Japanese)
Get a glimpse of machine learning in Python
I started machine learning with Python Data preprocessing
Build a Python machine learning environment with a container
Image collection Python script for creating datasets for machine learning
Build an interactive environment for machine learning in Python
Learn collaborative filtering along with Coursera Machine Learning materials
Run a machine learning pipeline with Cloud Dataflow (Python)
Tool MALSS (application) that supports machine learning in Python
[Python] Get the numbers in the graph image with OCR
Tool MALSS (basic) that supports machine learning in Python
Convert the image in .zip to PDF with Python
Build a machine learning application development environment with Python
Summary of the basic flow of machine learning with Python
Attempt to include machine learning model in python package
Cross-entropy to review in Coursera Machine Learning week 2 assignments
MALSS, a tool that supports machine learning in Python
Clustering text in Python
Learning Python with ChemTHEATER 03
"Object-oriented" learning with python
Learning Python with ChemTHEATER 05-1
Image format in Python
Learning Python with ChemTHEATER 02
Learning Python with ChemTHEATER 01
Image processing with Python
Machine learning A story about people who are not familiar with GBDT using GBDT in Python
Machine learning with Jupyter Notebook in OCI Always Free environment (2019/12/17)
The result of Java engineers learning machine learning in Python www
Exploring image filter parameters with blackbox optimization in Python Note
Create a python machine learning model relearning mechanism with mlflow
Machine learning environment settings based on Python 3 on Mac (coexistence with Python 2)
Image processing with Python (Part 2)
Machine learning learned with Pokemon