加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

关于PGM格式图像读写

(2013-01-16 16:50:25)
标签:

杂谈

分类: 常用工具
一、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

阅读 收藏 喜欢 打印举报/Report
前一篇:有感觉的歌
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有