function [img, map] = readppm(filename) % READPPM reads a PPM image file % [IMG, MAP] = READPPM(FILENAME) reads the PPM image file specified by % FILENAME and returns the image data in IMG and the colormap in MAP. % If the file is not a PPM image file, an error is thrown. % Open the file fid = fopen(filename, 'r'); if (fid < 0) error('Unable to open file'); end % Read the header header = fgetl(fid); if (~strcmp(header, 'P6')) fclose(fid); error('Invalid PPM file'); end dims = fscanf(fid, '%d %d\n', 2); maxval = fscanf(fid, '%d\n', 1); % Read the image data img = uint8(zeros(dims(2), dims(1), 3)); data = fread(fid, [3 dims(1)*dims(2)], 'uint8'); img(:,:,1) = reshape(data(1,:), dims(1), dims(2))'; img(:,:,2) = reshape(data(2,:), dims(1), dims(2))'; img(:,:,3) = reshape(data(3,:), dims(1), dims(2))'; % Close the file fclose(fid); % Create the colormap map = []; end 索引超出数组范围。应该怎么修改上述代码
时间: 2024-01-24 12:02:06 浏览: 19
在读取图像数据时,使用reshape函数时,应该将dims(2)和dims(1)的位置交换。修改后的代码如下:
```
function [img, map] = readppm(filename)
% READPPM reads a PPM image file
% [IMG, MAP] = READPPM(FILENAME) reads the PPM image file specified by
% FILENAME and returns the image data in IMG and the colormap in MAP.
% If the file is not a PPM image file, an error is thrown.
% Open the file
fid = fopen(filename, 'r');
if (fid < 0)
error('Unable to open file');
end
% Read the header
header = fgetl(fid);
if (~strcmp(header, 'P6'))
fclose(fid);
error('Invalid PPM file');
end
dims = fscanf(fid, '%d %d\n', 2);
maxval = fscanf(fid, '%d\n', 1);
% Read the image data
img = uint8(zeros(dims(1), dims(2), 3));
data = fread(fid, [3 dims(1)*dims(2)], 'uint8');
img(:,:,1) = reshape(data(1,:), dims(1), dims(2))';
img(:,:,2) = reshape(data(2,:), dims(1), dims(2))';
img(:,:,3) = reshape(data(3,:), dims(1), dims(2))';
% Close the file
fclose(fid);
% Create the colormap
map = [];
end
```