- 目标:将一张图片通过减少颜色进行压缩;
- 问题描述:
一张128*128的RGB图片,初始化数据是一个三纬矩阵:128*128*3,前两个纬度是点的位置,第三纬度对应RGB三色数值;
每中颜色是8位取值0-255;255*255*255种颜色,使用16种颜色进行压缩;
- 问题转换:
将原始图形转换为128*128行3列的样本数据,寻找16个聚类中心进行分类,然后将原来样本替换为聚类中心,重绘图形;
- 过程(各个函数代码请看AI-017: 练习:K-means Clustering):
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));
运行结果: