1

I am writing a short Matlab script to use im2bw to calculate the area of objects in the image. I am trying to validate that the areas are being calculated correctly, but on the reference image I am using the last square's area is 2% off and I cannot figure out why.


myFolder = 'Your Directory';
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '*.png'); % Change to whatever pattern you need.
theFiles = dir(filePattern);

for k = 1 : length(theFiles)
    baseFileName = theFiles(k).name;
    fullFileName = fullfile(theFiles(k).folder, baseFileName);
    
    J = imread(fullFileName);
    %J = imcrop(I,[500,200,4400,3500]);
    BW = im2bw(J,0.3);
    BW2 = imcomplement(BW);
    BW3 = imfill(BW2,4,'holes');
    
    %figure(1)
    %imshowpair(I,BW3,'montage')

    stats = regionprops(BW3,'area','PixelList','majoraxislength','minoraxislength');


    area = zeros(size(stats));
    for i = 1:size(stats,1)
        area(i) = stats(i).Area;
    end
    scale = 1e-6;
    %scale = 3.134755344e-8;
    cutoff = 0;
    area = area*scale;
    stats(area<cutoff)=[];
    area(area<cutoff)=[];
    
    writematrix(area,'Your Directory','WriteMode','append')
end

    figure(1)
    imshowpair(J,BW3,'montage')

The image is 1000x1000 the squares are 20x20, 100x100, 100x200, 200x200 respectively.

I assumed the reference image in reality was 1mx1m and scaled accordingly, but the 200x200 square seems to not come out exactly right.

0 Answers0