CImage 获取HBITMAP句柄与HBITMAP转IplImage

来源:互联网 发布:淘宝上买电棍怎么搜索 编辑:程序博客网 时间:2024/06/11 05:19

CImage 获取HBITMAP句柄:

#include <atlimage.h>char *fImgPath=" img path";CString fimgp=fImgPath;CImage fcimage;fcimage.Load(fimgp);HBITMAP fhandle = fcimage.Detach();
HBITMAP转IplImage

IplImage* hBitmapToIpl(HBITMAP hBmp)          {        BITMAP bmp;    GetObject(hBmp,sizeof(BITMAP),&bmp);    // get channels which equal 1 2 3 or 4    // bmBitsPixel :   // Specifies the number of bits    // required to indicate the color of a pixel.    int nChannels = bmp.bmBitsPixel == 1 ? 1 : bmp.bmBitsPixel/8 ;   // get depth color bitmap or grayscale   int depth = bmp.bmBitsPixel == 1 ? IPL_DEPTH_1U : IPL_DEPTH_8U;    // create header image   IplImage* img = cvCreateImage(cvSize(bmp.bmWidth,bmp.bmHeight),depth,nChannels);   // allocat memory for the pBuffer   BYTE *pBuffer = new BYTE[bmp.bmHeight*bmp.bmWidth*nChannels];    // copies the bitmap bits of a specified device-dependent bitmap into a buffer   GetBitmapBits(hBmp,bmp.bmHeight*bmp.bmWidth*nChannels,pBuffer);    // copy data to the imagedata   memcpy(img->imageData,pBuffer,bmp.bmHeight*bmp.bmWidth*nChannels);   delete pBuffer;    // create the image   IplImage *dst = cvCreateImage(cvGetSize(img),IPL_DEPTH_8U,1); //cvCvtColor(img, dst, CV_RGB2GRAY);// convert color if (img->nChannels==3){cvCvtColor(img,img,CV_BGRA2BGR);}//cvReleaseImage(&img); return img;   } 

网上所找代码基本都是:

  1. // create the image   
  2.     IplImage *dst = cvCreateImage(cvGetSize(img),img->depth,3);   
  3.     // convert color   
  4.     cvCvtColor(img,dst,CV_BGRA2BGR);   
  5.     cvReleaseImage(&img);   
  6.     return dst;  

但是这样的话当待读取图片是单通道灰度图时会报错。

1 0