Detect Actual Object Size using MATLAB

Actual Object size and size appears on camera varies, as you go closer to object, the size appear larger and as go far away from the object, size decreases on the camera view. To detect the actual object size on camera, an algorithm is available using Matlab.



filename = ‘abc.jpg’;

info = imfinfo(filename);

thres = graythresh(I);
I2=~(im2bw(I, thres));

cmp = bwconncomp(I2);
S = regionprops(cmp, ‘BoundingBox’);
x= S(1).BoundingBox(3);
y= S(1).BoundingBox(4);

res = info.ResolutionUnit;
resX = info.XResolution;
resY = info.YResolution;

if(strcmp(res, ‘Inch’))
lebar = 2.54 * x / resX;
tinggi = 2.54 * y / resY;
lebar = x /resX;
tinggi = y / resY;

fprintf(‘X Resolution = %.2f %s\n’, resX, res);
fprintf(‘Y Resolution = %.2f %s\n’, resY, res);
disp(‘Size of Object:’);
fprintf(‘Width = %.2f cm\n’, lebar);
fprintf(‘Height = %.2f cm\n’, tinggi);


Object Size Detection



Download Object size detection Matlab Code (681 Bytes)

Possible Errors:

There is a chance that Matlab does not detect XResolution, YResolution or ResolutionUnit or gives an error of imfinfo, this code is tested on MATLAB 2016a and it is working correctly.

The solution to missing or invalid command / parameter XResolution, YResolution or ResolutionUnit is to check the camera, some cameras are not supported or add limited information to images taken, like laptops add limited information to images taken and they do not add XResolution, YResolution, and ResolutionUnit. The images that we took for testing were taken from Smart Phone cameras, experimented on Samsung Galaxy J7 smartphone.

To check whether the camera is supported or not, take any picture with that camera and in Matlab use imfinfo(path to pic), you will get result like:

imfinfo XResolution, YResolution and ResolutionUnit

If you don’t get XResolution, YResolution and ResolutionUnit then that camera is not supported for this algorithm.

Leave a Reply

Your email address will not be published.