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));

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

铭记北宸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值