OpenCV的类型转换问题(BYTE、IplImage、Mat等)

1、BYTE转IplImage(需要每行字节对齐)

Mat中的图像数据是不对齐的,而IplImage中的图像数据是4字节对齐的

所以在访问IplImage图像数据的时候,要特别注意widthStep这个属性,每行的字节数不是width*nchannels而是widthStep,因为每行可能会有字节填充的


IplImage *prou_GetImage(CvSize size, UINT8 *ImgData,int nDepth, int nChannels)
{
IplImage *img_Image = cvCreateImage(size,nDepth,nChannels);
cvZero(img_Image);


int nWidthStep = img_Image->widthStep;
for ( int i = 0; i<size.height;i++ )
{
for ( int j=0;j<size.width;j++)
{
for(int n=0;n<nChannels;n++)
{
((uchar *)(img_Image->imageData + i*nWidthStep))


[j*nChannels + n] = ImgData[i*nWidthStep + j*nChannels + n];
}
}
}
return img_Image;
}


int nImgType = (int)fImgType;
int nTmgType = (int)fTmgType;
int nImgChannel = nImgType == 0 ? 1 : 3;
int nTmgChannel = nTmgType == 0 ? 1 : 3;


CvSize size;
size.width  = (int)((fImgWidth*1000+1)/1000);
size.height = (int)((fImgHeight*1000+1)/1000);


CvSize sizeTemp;
sizeTemp.width  = (int)((fTmgWidth*1000+1)/1000);
sizeTemp.height = (int)((fTmgHeight*1000+1)/1000);


  IplImage *img_Image = prou_GetImage(size, image_data,IPL_DEPTH_8U,3);
  IplImage *img_Temp  = prou_GetImage(sizeTemp, temp_data,IPL_DEPTH_8U,3);






2、IplImage转Mat


IplImage *img_Image = cvCreateImageHeader(size,IPL_DEPTH_8U,nImgChannel);
IplImage *img_Temp  = cvCreateImageHeader(sizeTemp,IPL_DEPTH_8U,nTmgChannel);

cvSetData(img_Image, image_data, img_Image->widthStep);
cvSetData(img_Temp, temp_data, img_Temp->widthStep);


3、BYTE转Mat

IplImage *img_Image = cvCreateImageHeader(size,IPL_DEPTH_8U,nImgChannel);
IplImage *img_Temp  = cvCreateImageHeader(sizeTemp,IPL_DEPTH_8U,nTmgChannel);

  cvSetData(img_Image, image_data, img_Image->widthStep);
  cvSetData(img_Temp, temp_data, img_Temp->widthStep);


int lineByteImg = (img_Image->widthStep + 3)/4*4;
Mat iMat(size.height, size.width, CV_8UC3, image_data, lineByteImg); 

int lineByteTmg = (img_Temp->widthStep + 3)/4*4;  
Mat tMat(sizeTemp.height, sizeTemp.width, CV_8UC3, temp_data, lineByteTmg); 

你可能感兴趣的:(opencv)