MATLAB Answers

Can anybody plz explain this code,specifically the 5th line..

1 view (last 30 days)
Sumeet Badgujar
Sumeet Badgujar on 26 Oct 2018
Commented: Walter Roberson on 27 Oct 2018
abc=input('Enter image name or path');
a=imread(abc);
imshow(a);
b=size(a);
c=b(1)*b(2)/1024;
disp(fprintf('Name of image: %s',abc))
disp(fprintf('Size of the image is %f kB',c))

Answers (3)

OCDER
OCDER on 26 Oct 2018
An image is often represented as a MxNx3 matrix, where each element of a matrix is a uint8 value ranging from 0 to 255 (this is 1 byte of data. 1 byte = 8 bits = value from 0 to 255).
Thus, each pixel of an image is of size 1x1x3 matrix for the Red, Green, and Blue values. With that said, that code line 5 is incorrect if dealing with color images, as each pixel actually requires 3 bytes of data (Ex. White = [255, 255, 255] = 3 bytes)
image size should be:
c = prod(b) /1024 ; %for kB of data
If you have the liberty of editing the code, change the variable names to be more descriptive.
ImageSizeKB = prod(b) / 1024; %prod(b) will do b(1)*b(2)*b(3) = MxNx3 = total bytes in image
Another way to get image size is by using iminfo FileSize
ImageInfo = iminfo(abc);
ImageSizeKB = ImageInfo.FileSize / 1024;

madhan ravi
madhan ravi on 26 Oct 2018
a small example to illustrate
a = rand(4,3)
b = size(a)
b(1)
b(2)
  3 Comments

Sign in to comment.


Image Analyst
Image Analyst on 26 Oct 2018
This is BAD code and has several errors. What line 5 does is to try to compute the number of pixels and then kilobytes. b(1) is the number of rows. b(2) is the number of columns multiplied by the number of color channels. Then if you multiply them together you get the number of pixels, and if you assume they're 1 byte pixels and divide by 1024 you get kilobytes. Here is some less bad code:
fileName = input('Enter image name or path : ', 's')
theImage = imread(fileName);
imshow(theImage);
axis('on', 'image');
sizeDimensions = size(theImage);
sizeInBytes = sizeDimensions(1)*sizeDimensions(2)/1024
fileInfo = dir(fileName)
fprintf('Name of image: %s\n', fileName)
fprintf('Size of the image is %d bytes, or %.1f kB\n', fileInfo.bytes, fileInfo.bytes / 1024)
but it's still not that robust or user friendly. Please review these links:
I would not look to that programmer as a paragon of MATLAB code writing ability.
  3 Comments
Walter Roberson
Walter Roberson on 27 Oct 2018
Image file sizes on disk represent sizes including any headers and comments (such as EXIF information), and take into account any compression (which might be lossy) that has been used. The size of the disk file can end up being larger than the amount of memory required to store the image in memory, but the file size could also end up being much less than is required to store the image in main memory if the compression is strong.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!