最近使用matlab读取2进制pgm文件中的像素,根据每个栅格占(SizeCell*SizeCell)像素的需求生成二维矩阵,在此记录
完整代码如下:
function GridMap = ReadPGM(PGMname,SizeCell)
% PGMname = "C:\Users\Administrator\Desktop\AreaSearch\esdf\nav4.pgm";
info = imfinfo(PGMname); % 读取PGM文件的信息
% 尝试以二进制打开文件
fileID = fopen(PGMname,'r','b');
if fileID ==-1
error("Failed to open file:%s",PGMname);
end
PGMdata = fread(fileID); %将pgm文件中的所有数据存入PGMdata中
fclose(fileID); %关闭文件
magicNumber = info.Format;% 读取图片类型
if magicNumber~="PGM"
error("不是有效PGM文件");
end
if ~strcmp(info.FormatVersion,'P5')
error("不是2进制PGM文件");
end
% 读取剩余的文件信息(宽度,高度,最大灰度值)
width = info.Width;
height = info.Height;
dataBeginIndex = info.FileSize-width*height+1;
pixelMatrix = reshape(PGMdata(dataBeginIndex:end),width,height);% 将数据重塑为二维矩阵
imshow(pixelMatrix,[]);
colorbar;
title("PGM栅格地图");
% SizeCell = 5;
% 由于像素矩阵的行和列不一定能够被SizeCell整除,所以会在外面加一层表示障碍物
TureMapRows = fix(width/SizeCell);
TureMapCols = fix(height/SizeCell);
MapRows = TureMapRows+1;
MapCols = TureMapCols+1;
GridMap = zeros(MapRows,MapCols);
for contR = 1:MapRows
for contC = 1:MapCols
isFree = 1;
for contI = 1:SizeCell
for contJ = 1:SizeCell
pixelrow = (contR-1)*SizeCell+contI;
pixelcol = (contC-1)*SizeCell+contJ;
if pixelrow>width||pixelcol>height
isFree = 0;
contI = SizeCell;
break;
end
if pixelMatrix(pixelrow,pixelcol)~=254
isFree = 0;
contI = SizeCell;
break;
end
end
end
if isFree==1
GridMap(contR,contC) = 0;
else
GridMap(contR,contC) = 1;
end
end
end
% DrawMap(GridMap);
end