How to create .pgm image from text file?

Hello
I have a .txt file in the following format(see attached file):
line 1: integer height
line 2: integer width
line 3: float ratio
line 4: int size
line 5: int start
line 6: int goal
The next lines from 7 to height must be stored in a matrix height*width
The matrix is matrix of integers ( 0s and 100s)
The 0s must be converted to white pixels(free spaces) while 100s must be converted to black pixels(obstacles), so the image is a map that can be used in robot navigations.
How can I read this file and convert the matrix into .pgm image file.
Thanks a lot in advance,

1 comentario

Eman Almoaili
Eman Almoaili el 18 de Nov. de 2020
Editada: Eman Almoaili el 18 de Nov. de 2020
It works. Now I have .pgm image from the matrix in the tex file. I cannot attach the .pgm file here as it is not supported. However, the image is very small. How can I create the image so that each pixel can be seen clearly?
In fact, the image is a 2d grid generated as a map for robotics applications, the width and height can be 8,16, 32, .. up to 256. Thus, I need a clear image.
% read the text file and store variables
fid = fopen('map2.txt','r');
lines = textscan(fid,'%s','delimiter','\n');
fclose(fid);
lines = lines{1};
height = sscanf(lines{1},'%d');
width = sscanf(lines{2},'%d');
Ratio = sscanf(lines{3},'%f');
Size = sscanf(lines{4},'%d');
start = sscanf(lines{5},'%d');
goal = sscanf(lines{6},'%d');
% parse lines 7-height, so M is a martix height*width
M = zeros(height,width);
for i = 1:height
M(i,:) = sscanf(lines{6+i},'%d')';
end
% Text to image conversion
% Create a matrix of the desired image dimensions
% In this case, height and width
p = zeros(height,width);
% Calculate the pixel values using a nested while loop
y = 1;
while y <= height
x = 1;
while x <= width
if M(x,y) == 0
p(y,x) = 255; %white pixel
else %M(height,width) == 100
p(y,x) = 0; %black pixel
end
x = x + 1;
end
y = y + 1;
end
% Write pixels to a PGM image file
% Open a file for writing
fid = fopen('image.pgm','w');
% Write the PGM image header to the file
fprintf(fid,'P2\n');
fprintf(fid,'%d %d\n', width, height);
fprintf(fid,'255\n');
% Write the pixel values from the matrix into
% the file
y = 1;
while y <= height
x = 1;
while x <= width
fprintf(fid, '%03d ', p(y,x));
x = x + 1;
end
fprintf(fid, '\n');
y = y + 1;
end
% Close the file
fclose(fid);

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Etiquetas

Preguntada:

el 17 de Nov. de 2020

Editada:

el 18 de Nov. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by