Skip to content

Instantly share code, notes, and snippets.

@nikAizuddin
Last active October 22, 2018 00:10
Show Gist options
  • Save nikAizuddin/50a43423e09498df659cbea95b947fb5 to your computer and use it in GitHub Desktop.
Save nikAizuddin/50a43423e09498df659cbea95b947fb5 to your computer and use it in GitHub Desktop.
Image compression using KMeans
%% Global configurations.
SOURCE_IMAGE = 'lena.png';
N_CENTROIDS = 3;
%% Load source image and pre-processed for KMeans.
src = imread(SOURCE_IMAGE);
% Convert uint8 pixel type into double precision type. Also normalizes the
% pixel from range [0, 255] into [0.0, 1.0].
src = im2double(src);
% Reshape the image into a list of pixels. Before reshape, it is
% important to store the source image's original size in order to
% reshape it back into its original size.
[height, width, n_channels] = size(src);
src = reshape(src, [width*height, n_channels]);
%% Generate codebook and also encode the source image.
[encoded, codebook] = kmeans(src, N_CENTROIDS);
% At this point, the variable encoded is the encoded source image that
% contains index number from the codebook.
%% Example how to display the encoded image.
% Since the encoded contains index number from the codebook, map the
% codebook into the encoded indices.
decoded = codebook(encoded, :);
% Reshape the source image back into its original shape.
decoded = reshape(decoded, [height, width, n_channels]);
% Since the im2double() function normalizes the pixel into range
% [0.0, 1.0], it should be restored back into its 8-bit data type with
% pixel value range [0, 255].
decoded = uint8(decoded * 255);
imshow(decoded);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment