Search code examples
matlabarea

Area calculation in MATLAB


I am working on a paper and I need to find out the area of the region having color black from the image that I have attached.

Original image

I have done some processing by using threshold and complimenting the image.Processed image Now I'm having a problem finding the area of the black colored region. Can someone please help? I'm new to MATLAB.

Here is my code :

img1=imread('C:/Users/Allan/Desktop/unnamed1.jpg');
imshow(img1)

img1=rgb2gray(img1);
imshow(img1)

img2=im2bw(img1,graythresh(img1));
imshow(img2)

img2=~img2;
imshow(img2)

B = bwboundaries(img2);
imshow(img2)
hold on

for k = 1:length(B)
boundary = B{k};
plot(boundary(:,2), boundary(:,1), 'g', 'LineWidth', 0.2)
end

Solution

  • use regionprops or bwarea:

    % take the NOT image
    bw = ~img2;
    % find individual regions
    cc = bwconncomp(bw);
    % find area for each black region
    props = regionprops(cc,{'Area','Centroid'});
    regionArea = [props(:).Area];
    % find area of total black region
    totalArea = bwarea(bw);
    % plotting
    for ii = find(regionArea > 100)
        c = props(ii).Centroid;
        text(c(1),c(2),num2str(regionArea(ii)),'Color','b',...
            'HorizontalAlignment','center','VerticalAlignment','middle',...
            'FontWeight','bold');
    end
    

    enter image description here