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;
}
网上所找代码基本都是:
- // create the image
- IplImage *dst = cvCreateImage(cvGetSize(img),img->depth,3);
- // convert color
- cvCvtColor(img,dst,CV_BGRA2BGR);
- cvReleaseImage(&img);
- return dst;
但是这样的话当待读取图片是单通道灰度图时会报错。