读文件
1 @4 l# |, g3 m/ X$ g$ p+ t
%function disp_ pgm ( pgm _image_name)
%不支持文件中有注释
pgm _image_name='tmp. pgm ';
f = fopen( pgm _image_name,'r');
if f == -1
error(['Could not open file ', pgm _image_name]);
end / t2 V; a( c$ l1 A$ C' j6 P
[imgsize, num]=fscanf(f, 'P5\n%d\n%d\n255\n'); . J1 [& _. g! k; I( x$ E
if num~=2,error('error num');end
image=[];
for h=1:imgsize(2)
image=[image fread(f,imgsize(1),'uint8')];
end
image=image.'; 3 ?4 @# c% O% D2 O v3 ]
fclose(f); . I, \4 B! Y( @5 r7 \" n
imshow(image);
写文件
% Load image
% image = imread(imageFile);
% If you have the Image Processing Toolbox, you can uncomment the following 9 p, m5 N" g7 v4 [! j2 P
% lines to allow input of color images, which will be converted to grayscale.
if isrgb(image)
image = rgb2gray(image); 6 W/ I+ U; o9 B; | I0 c3 U
end + q7 [1 P, r: I& t& e) m/ {
[rows, cols] = size(image);
% Convert into PGM imagefile, readable by "keypoints" executable
f = fopen('tmp. pgm ', 'w');
if f == -1 / p/ D' b: r- F2 q
error('Could not create file tmp. pgm .'); ' J/ R' e6 F! b3 L" ?- `
end & G( C& n/ {8 I' ?
fprintf(f, 'P5\n%d\n%d\n255\n', cols, rows); 1 x9 ?5 x4 M' ^
fwrite(f, image', 'uint8');
%function disp_ pgm ( pgm _image_name)
%不支持文件中有注释
pgm _image_name='tmp. pgm ';
f = fopen( pgm _image_name,'r');
if f == -1
error(['Could not open file ', pgm _image_name]);
end / t2 V; a( c$ l1 A$ C' j6 P
[imgsize, num]=fscanf(f, 'P5\n%d\n%d\n255\n'); . J1 [& _. g! k; I( x$ E
if num~=2,error('error num');end
image=[];
for h=1:imgsize(2)
image=[image fread(f,imgsize(1),'uint8')];
end
image=image.'; 3 ?4 @# c% O% D2 O v3 ]
fclose(f); . I, \4 B! Y( @5 r7 \" n
imshow(image);
写文件
% Load image
% image = imread(imageFile);
% If you have the Image Processing Toolbox, you can uncomment the following 9 p, m5 N" g7 v4 [! j2 P
% lines to allow input of color images, which will be converted to grayscale.
if isrgb(image)
image = rgb2gray(image); 6 W/ I+ U; o9 B; | I0 c3 U
end + q7 [1 P, r: I& t& e) m/ {
[rows, cols] = size(image);
% Convert into PGM imagefile, readable by "keypoints" executable
f = fopen('tmp. pgm ', 'w');
if f == -1 / p/ D' b: r- F2 q
error('Could not create file tmp. pgm .'); ' J/ R' e6 F! b3 L" ?- `
end & G( C& n/ {8 I' ?
fprintf(f, 'P5\n%d\n%d\n255\n', cols, rows); 1 x9 ?5 x4 M' ^
fwrite(f, image', 'uint8');
fclose(f);
本文转自博客园知识天地的博客,原文链接:matlab读写pgm文件(转),如需转载请自行联系原博主。