使用matlab读取2进制pgm文件生成栅格地图

最近使用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

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值