matlab代码读写PPM和PGM图像
时间: 2023-11-24 10:05:17 浏览: 100
pbm/pgm/ppm图片的读写(Matlab)
4星 · 用户满意度95%
以下是使用MATLAB读取和写入PPM和PGM图像的示例代码:
读取PPM图像:
```matlab
function img = read_ppm(filename)
% Open the file for reading
fid = fopen(filename, 'rb');
% Read the header
header = fgets(fid);
% Check if the file is P6 format
if ~strcmp(header, 'P6\n')
error('Not a P6 PPM file');
end
% Read the width, height, and max value
w = fscanf(fid, '%d', 1);
h = fscanf(fid, '%d', 1);
maxval = fscanf(fid, '%d', 1);
% Read the image data
data = fread(fid, [3, w * h], 'uint8');
% Close the file
fclose(fid);
% Reshape the data and convert to double
img = double(reshape(data, [3, w, h]));
img = permute(img, [3, 2, 1]);
% Normalize to [0,1] range
img = img / maxval;
end
```
写入PPM图像:
```matlab
function write_ppm(filename, img)
% Open the file for writing
fid = fopen(filename, 'wb');
% Write the header
fprintf(fid, 'P6\n');
% Write the width, height, and max value
[h, w, d] = size(img);
fprintf(fid, '%d %d\n', w, h);
fprintf(fid, '255\n');
% Convert to uint8 and write the data
data = uint8(round(img * 255));
data = permute(data, [3, 2, 1]);
fwrite(fid, data, 'uint8');
% Close the file
fclose(fid);
end
```
读取PGM图像:
```matlab
function img = read_pgm(filename)
% Open the file for reading
fid = fopen(filename, 'rb');
% Read the header
header = fgets(fid);
% Check if the file is P5 format
if ~strcmp(header, 'P5\n')
error('Not a P5 PGM file');
end
% Read the width, height, and max value
w = fscanf(fid, '%d', 1);
h = fscanf(fid, '%d', 1);
maxval = fscanf(fid, '%d', 1);
% Read the image data
data = fread(fid, [w, h], 'uint8');
% Close the file
fclose(fid);
% Convert to double and normalize to [0,1] range
img = double(data') / maxval;
end
```
写入PGM图像:
```matlab
function write_pgm(filename, img)
% Open the file for writing
fid = fopen(filename, 'wb');
% Write the header
fprintf(fid, 'P5\n');
% Write the width, height, and max value
[h, w] = size(img);
fprintf(fid, '%d %d\n', w, h);
fprintf(fid, '255\n');
% Convert to uint8 and write the data
data = uint8(round(img * 255));
data = data';
fwrite(fid, data, 'uint8');
% Close the file
fclose(fid);
end
```
注意,在这些示例代码中,我们假设PPM和PGM图像的最大值为255。如果您的图像最大值不同,请相应地修改代码。
阅读全文