matlab代码实现读写PPM和PGM图像
时间: 2023-12-06 11:13:11 浏览: 136
下面是MATLAB代码实现读写PPM和PGM图像的示例:
读取PPM图像:
```matlab
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
```
读取PGM图像:
```matlab
function [img, map] = readpgm(filename)
% READPGM reads a PGM image file
% [IMG, MAP] = READPGM(FILENAME) reads the PGM image file specified by
% FILENAME and returns the image data in IMG and the colormap in MAP.
% If the file is not a PGM 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, 'P5'))
fclose(fid);
error('Invalid PGM 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)));
data = fread(fid, [1 dims(1)*dims(2)], 'uint8');
img(:,:) = reshape(data, dims(1), dims(2))';
% Close the file
fclose(fid);
% Create the colormap
map = [];
end
```
写PPM图像:
```matlab
function writeppm(filename, img)
% WRITEPPM writes a PPM image file
% WRITEPPM(FILENAME, IMG) writes the image data in IMG to the PPM image
% file specified by FILENAME.
% Open the file
fid = fopen(filename, 'w');
if (fid < 0)
error('Unable to open file');
end
% Write the header
fprintf(fid, 'P6\n');
fprintf(fid, '%d %d\n', size(img,2), size(img,1));
fprintf(fid, '255\n');
% Write the image data
fwrite(fid, permute(img, [3,1,2]), 'uint8');
% Close the file
fclose(fid);
end
```
写PGM图像:
```matlab
function writepgm(filename, img)
% WRITEPGM writes a PGM image file
% WRITEPGM(FILENAME, IMG) writes the image data in IMG to the PGM image
% file specified by FILENAME.
% Open the file
fid = fopen(filename, 'w');
if (fid < 0)
error('Unable to open file');
end
% Write the header
fprintf(fid, 'P5\n');
fprintf(fid, '%d %d\n', size(img,2), size(img,1));
fprintf(fid, '255\n');
% Write the image data
fwrite(fid, img', 'uint8');
% Close the file
fclose(fid);
end
```
注意:以上代码中的PPM和PGM格式均为二进制格式。如果需要读取和写入ASCII格式的PPM和PGM图像,请相应地更改代码。
阅读全文