关于PGM格式图像读写

来源:互联网 发布:知乎回答问题在哪里 编辑:程序博客网 时间:2024/05/22 20:07
一、matlab读写pgm文件
from:http://www.ilovematlab.cn/thread-4960-1-1.html
读文件
%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
[imgsize, num]=fscanf(f, 'P5\n%d\n%d\n255\n');
if num~=2,error('error num');end
image=[];
for h=1:imgsize(2)
    image=[image fread(f,imgsize(1),'uint8')];
end
image=image.';
fclose(f);
imshow(image);
写文件
% Load image
% image = imread(imageFile);
% If you have the Image Processing Toolbox, you can uncomment the following
  lines to allow input of color images, which will be converted to grayscale.
if isrgb(image)
   image = rgb2gray(image);
end
[rows, cols] = size(image);
% Convert into PGM imagefile, readable by "keypoints" executable
f = fopen('tmp.pgm', 'w');
if f == -1
    error('Could not create file tmp.pgm.');
end
fprintf(f, 'P5\n%d\n%d\n255\n', cols, rows);
fwrite(f, image', 'uint8');
fclose(f);

二、IplImage图像转换为p2或p5格式的pgm图像  
from:http://blog.163.com/czy_sysu/blog/static/130695599201010583910102/
void cvConvertImage2pgm(char* filename,IplImage* srcImage,int type)
{

int width=srcImage->width;
int height=srcImage->height;

FILE *pgmPict;
int rSize=width*height;
        int i,j;
pgmPict=fopen(filename,"w"); 
if(type==2)
{
fprintf(pgmPict,"P2\n");
}else if(type==5)
{
fprintf(pgmPict,"P5\n");
}
fprintf(pgmPict,"%d %d \n%d\n",width,height,255);
if(type==5)
{
                unsigned char temp=0;
for( i=0;i<srcImage->height;i++)
{
for( j=0;j<srcImage->width;j++)
{
temp=srcImage->imageData[i*srcImage->widthStep+j*3];
fwrite((void*)&temp,sizeof(unsigned char),1,pgmPict);
}
}
}
else if(type==2)
{
for( i=0;i<srcImage->height;i++)
{
for( j=0;j<srcImage->width;j++)
{
int temp=(int)srcImage->imageData[i*srcImage->widthStep+j*3];
if(temp<0)
temp+=256;
fprintf(pgmPict,"%d ",temp);
}
}
}
fclose(pgmPict);
}
0 0
原创粉丝点击