matlab读写pgm文件

读文件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 following9 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);
posted on 2012-02-16 14:45  知识天地  阅读(3856)  评论(0编辑  收藏  举报