close all 

%% 1
RGB = imread('pillsetc.png');
figure; imshow(RGB); title('Original image')

%% 2
I = rgb2gray(RGB);


figure;imhist(I)
threshold = graythresh(I);
bw = im2bw(I,threshold);
figure; imshow(bw); title('Threshold')

%% 3
bw = bwareaopen(bw, 30);
se = strel('disk',2);
bw = imclose(bw, se);
bw = imfill(bw, 'holes');
figure ; imshow(bw);

%% 4
[B, L] = bwboundaries(bw, 'noholes');

figure; imshow(label2rgb(L, @jet, [.5 .5 .5]))
hold on 
for k = 1:length(B)
    boundary = B{k};
    plot(boundary(:,2), boundary(:,1), 'w', 'LineWidth', 2)
end

%% 5
stats = regionprops(L, 'Area', 'Centroid');
thr = 0.94; 

for k=1:length(B)
    boundary = B{k};
    delta_sq = diff(boundary).^2; 
    
    perimeter = sum(sqrt(sum(delta_sq,2)));
    
    area = stats(k).Area;
    
    metric = 4*pi*area/perimeter^2;
    
    metric_string = sprintf('%2.2f', metric);
    
    if metric > threshold 
        centroid = stats(k).Centroid;
        plot(centroid(1), centroid(2), 'ko');
    end
    
    text(boundary(1,2) - 35, boundary(1,1) + 13, metric_string, 'Color', 'y', ... 
        'FontSize', 14, 'FontWeight', 'bold');
end
title(['Metrics close to 1 -> object approx. round'])


