close all;
clear clc;

%loading the image
I = imread("bird.png");
I = rgb2gray(I);

%calculating histogram vector
H = zeros(1, 256);
for i1 = 1:size(I,1)
    for i2 = 1:size(I,2)
         for idx = 1:256
             if I(i1, i2) == idx - 1
                  H(idx) = H(idx) + 1;
             end
         end
    end
end

stretched_I = zeros(size(I));
stretched_H = zeros(1,256);

double_I = im2double(I);

%calculating min and max intensity values of the image
minimum = min(double_I(:));
maximum = max(double_I(:));

%stretching the intensity values of the original image
for i1 = 1:size(double_I,1)
    for i2 = 1:size(double_I,2)
      stretched_I(i1, i2) = (255/(maximum - minimum)) * (double_I(i1, i2) - minimum);
    end
end

stretched_I = uint8(round(stretched_I));

%calculating the new histogram vector
for i1 = 1:size(stretched_I,1)
    for i2 = 1:size(stretched_I,2)
         for idx = 1:256
             if stretched_I(i1, i2) == idx - 1
                  stretched_H(idx) = stretched_H(idx) + 1;
             end
         end
    end
end

figure();

subplot(2,2,1);
imshow(I);
title('original grayscale image');

subplot(2,2,3);
bar(H);
title('histogram of the original input');
xlim([1,256]);

subplot(2,2,2);
imshow(stretched_I);
title('stretched image');

subplot(2,2,4);
bar(stretched_H);
title('stretched histogram');
xlim([1,256]);

