OpenCV中IplImage和单字节char*的相互转换

来源:互联网 发布:广告投放算法好吃 编辑:程序博客网 时间:2024/04/26 19:13

OpenCV中IplImage和单字节char*的相互转换



  1. 从 IplImage到 char* :  
  2. data = image->imageData //对齐的图像数据  
  3.      或者data = image->imageDataOrigin //未对齐的原始图像数据  
  4. 从 char* 到 IplImage:  
  5. image =cvCreateImageHeader(cvSize(width,height), depth, channels);  
  6. cvSetData(image, data, step);  
    

 step指定IplImage图像每行占的字节数。需要注意是,在释放空间时不能直接使用cvReleaseImage,而需cvReleaseImageHeader,然后再delete data,这也是OpenCV里边“自己管理内存”的思想。

IplImage有两个属性非常值得关注,稍不留神就会导致错误:一是width属性;二是widthStep属性。前者是表示图像的每行像素数,后者指表示存储一行像素需要的字节数。


[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. IplImage *img=cvLoadImage(m_strfile,0);  
  2. int height,widht,step,channel;  
  3. height=img->height;  
  4. widht=img->width;  
  5. step=img->widthStep;  
  6. channel=img->nChannels;  

可以看出IplImage的widthStep并不等于width*channel,它是4字节对齐的。

举例:图像灰度化


  1. IplImage *img=cvLoadImage(m_strfile,0);  
  2. int height,widht,step,channel;  
  3. height=img->height;  
  4. widht=img->width;  
  5. step=img->widthStep;  
  6. channel=img->nChannels;  

可以看出IplImage的widthStep并不等于width*channel,它是4字节对齐的。

举例:图像灰度化

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. //Width-图像宽  
  2. //Height-图像高  
  3. //pData-输入图像数据指针(DIB)  
  4. //lineByteIn-输入图像每行字节数  
  5. //pDataOut-输出图像数据指针  
  6. IplImage *img= cvCreateImageHeader(cvSize(Width,Height),IPL_DEPTH_8U,3);  
  7. cvSetData(img,pData,lineByteIn);  
  8. IplImage *des_gray=cvCreateImage(cvGetSize(img),img->depth,1);  
  9. cvCvtColor(img,des_gray,CV_RGB2GRAY);  
  10. memcpy(pDataOut,des_gray->imageData,des_gray->widthStep*des_gray->height);  
  11. cvReleaseImageHeader(&img);  
  12. cvReleaseImage(&des_gray);  

0 0
原创粉丝点击