1. 程式人生 > >AI-019: 練習:Image compression with K-means

AI-019: 練習:Image compression with K-means

  • 目標:將一張圖片通過減少顏色進行壓縮;
  • 問題描述:

一張128*128的RGB圖片,初始化資料是一個三緯矩陣:128*128*3,前兩個緯度是點的位置,第三緯度對應RGB三色數值;

每中顏色是8位取值0-255;255*255*255種顏色,使用16種顏色進行壓縮;

  • 問題轉換:

將原始圖形轉換為128*128行3列的樣本資料,尋找16個聚類中心進行分類,然後將原來樣本替換為聚類中心,重繪圖形;

1. 將原始圖形轉換為128*128行3列的樣本資料

%  Load an image of a bird
A = double(imread('tank1.png'));

A = A / 255; % Divide by 255 so that all values are in the range 0 - 1

% Size of the image
img_size = size(A);

% Reshape the image into an Nx3 matrix where N = number of pixels.
% Each row will contain the Red, Green and Blue pixel values
% This gives us our dataset matrix X that we will use K-Means on.
X = reshape(A, img_size(1) * img_size(2), 3);

2. 用K-means聚類演算法尋找16個最佳的聚類中心

% Run your K-Means algorithm on this data
% You should try different values of K and max_iters here
K = 16; 
max_iters = 10;

% Run K-Means
[centroids, idx] = runkMeans(X, initial_centroids, max_iters);

3. 將原來樣本替換為聚類中心,重繪圖形

% Find closest cluster members
idx = findClosestCentroids(X, centroids);

% We can now recover the image from the indices (idx) by mapping each pixel
% (specified by its index in idx) to the centroid value
X_recovered = centroids(idx,:);

% Reshape the recovered image into proper dimensions
X_recovered = reshape(X_recovered, img_size(1), img_size(2), 3);

% Display the original image 
subplot(1, 2, 1);
imagesc(A); 
title('Original');

% Display compressed image side by side
subplot(1, 2, 2);
imagesc(X_recovered)
title(sprintf('Compressed, with %d colors.', K));

執行結果: