关于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/
int i,j;
unsigned
char temp=0;
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
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)
end
image=image.';
fclose(f);
imshow(image);
写文件
% Load image
% image = imread(imageFile);
% If you have the Image Processing Toolbox, you can uncomment the following
%
if isrgb(image)
end
[rows, cols] = size(image);
% Convert into PGM imagefile, readable by "keypoints" executable
f = fopen('tmp.pgm', 'w');
if f == -1
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;
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)
{
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);
}
前一篇:有感觉的歌
后一篇:转:c语言调用C++库