1. 程式人生 > >利用opencv把其它格式的圖片轉換為pgm格式程式碼

利用opencv把其它格式的圖片轉換為pgm格式程式碼

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); }