利用opencv把其它格式的图片转换为pgm格式代码

来源:互联网 发布:淘宝网医用输液瓶口贴 编辑:程序博客网 时间:2024/05/19 03:28

from:http://blog.163.com/czy_sysu/blog/static/130695599201010583910102/


在迹线变换traceall项目中,对输入的文件要求是p2和p5格式。而一般利用opencv处理的格式为IplImage,因此需要进行格式转换。关于pgm格式可以参考如下文档http://wenku.baidu.com/view/13371a4de518964bcf847cd0.html。下面给出实现代码:
/*
 *将IplImage转储为p5格式的图像
 *
 *filename:  保存的图像名称 
 *
 *srcImage:  输入的图像
 *
 *type:转换后pgm的类型,2--p2,5--p5
 */
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);
}

原创粉丝点击