CImage 获取HBITMAP句柄与HBITMAP转IplImage

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值