How I can read image with PPM format without imread and design PPM reader ?

54 views (last 30 days)
I want to read test.ppm image without imread and design PPM reader and open it with fopen and extract data from it after that show it with imshow.
Can you help me?

Sign in to comment.

Accepted Answer

DGM on 26 Nov 2021
Edited: DGM on 26 Nov 2021
Again, the documentation
As an example for this one image, consider the following.
% open the file and read the whole thing
fid = fopen('Barbara.pgm', 'r');
B = fread(fid,inf,'uint8=>char')';
% find header delimiters
ws = find(isspace(B),4,'first')
% get file parts (assuming no comments)
magicnum = B(1:ws(1)-1) % this is expected to be P5
% if P2, P3, or P6, do whatever is needed
imgeometry = [str2double(B(ws(1)+1:ws(2)-1)) str2double(B(ws(2)+1:ws(3)-1))]
maxgval = str2double(B(ws(3)+1:ws(4)-1)) % expected to be 255
imgdata = permute(reshape(double(B(ws(4)+1:end)),imgeometry),[2 1 3]);
% normalize the image for convenience
imgdata = imgdata/maxgval;
Note that this code is not robust and does not accomodate the existence of inline comments in the file. You'll have to deal with that.
This code also assumes that the max gray value stays below 256. If maxgval>255, then you'll have to do some reshaping and simple math because each pixel will be represented by byte pairs instead of single bytes.
If your project needs to read both PGM and PPM files of both types, then you'll have to conditionally handle those cases based on the magic number.
If you want an integer-class numeric array as output instead of a normalized floating-point array, you'll have to conditionally look at the max gray value and cast the image data accordingly.

Sign in to comment.

More Answers (2)

Walter Roberson
Walter Roberson on 25 Nov 2021
fopen the file and read it as a series of uint8. fclose(). Now use loadlibrary() to make a call to the libnetpbm library to decode the uint8 into an image.
By the way, is it a P3 or P6?
Walter Roberson
Walter Roberson on 26 Nov 2021
PPM files do not all have exactly the same layout. The very first item inside a PPM file gives information about which of the formats the rest of the file is in. Two of the most common formats are known by the codes P3 and P6.
If you need to be able to handle all possible PPM files, then you have to do notably more work than if you only have to handle one particular kind of PPM file.

Sign in to comment.

yanqi liu
yanqi liu on 26 Nov 2021
yes,sir,may be upload the ppm file to do some analysis

Community Treasure Hunt

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

Start Hunting!