clear; clc; close all;

levels = 3;
A = imread('taipei101.jpg');
[rows, cols, ~] = size(A);
B = double(reshape(A, [rows * cols, 3]));
[labels, C] = kmeans(B, levels);
D = zeros(length(labels), 3);
for i = 1 : levels
    mask = labels == i;
    for j = 1 : 3
        D(mask, j) = C(i, j);
    end
end
D = reshape(D, [rows, cols, 3]);
D = uint8(D);
figure('position', [100, 100, 600, 600]);
subplot(2, 1, 1); imshow(A);
subplot(2, 1, 2); imshow(D);