想把kinect V1.0设备获取到的彩色图显示在MFC的picture控件中,图的格式是opencv中的Mat矩阵,每秒30帧,显示相对还是比较流畅。整个接口由一个函数完成,函数无返回值,要求输入picture控件ID和Mat图像矩阵
函数:void showMatImgToWnd(CWnd* pWnd, const cv::Mat& img) |
1、首先,要进行输入检查,看Mat数据是否是有效的,如下图中所示
if (img.empty())
return;
2、定义位图数据结构,用以方便在图形设备接口(GraphicsDeviceInterface)上显示,也就是windows上的GDI
static BITMAPINFO *bitMapinfo = NULL;
static bool First = TRUE;
if (First)
{
BYTE *bitBuffer = new BYTE[40 + 4 * 256];//开辟一个内存区域
3、开发内存空间,并初始化,按下图中所示那样即可
memset(bitBuffer, 0, 40 + 4 * 256);
/* void *memset(void *s, int c, size_t n)
将已开辟内存空间s的首n个字节的值设为值c
*/
4、定义位图相关信息,并和输入数据Mat图联系起来
5、在获取控件的客户区,并设置图像的显示模式,SetStretchBltMode是Windows GDI函数,功能为该函数可以设置指定设备环境中的位图拉伸模式。COLORONCOLOR:删除像素。该模式删除所有消除的像素行,不保留其信息。
CRect drect;
pWnd->GetClientRect(drect); //pWnd指向CWnd类的一个指针
CClientDC dc(pWnd);
HDC hDC = dc.GetSafeHdc(); //HDC是Windows的一种数据类型,是设备描述句柄;
SetStretchBltMode(hDC, COLORONCOLOR);
6、完成上述后,将内存中的图像数据拷贝到屏幕上,执行如下图中所示
StretchDIBits(hDC,
0,
0,
drect.right, //显示窗口宽度
drect.bottom, //显示窗口高度
0,
0,
img.cols, //图像宽度
img.rows, //图像高度
img.data,
bitMapinfo,
DIB_RGB_COLORS,
SRCCOPY
);
具体代码:
void CCam_MFC_6Dlg::showMatImgToWnd(CWnd* pWnd, const cv::Mat& img)
{
if (img.empty())
return;
static BITMAPINFO *bitMapinfo = NULL;
static bool First = TRUE;
if (First)
{
BYTE *bitBuffer = new BYTE[40 + 4 * 256];//开辟一个内存区域
if (bitBuffer == NULL)
{
return;
}
First = FALSE;
memset(bitBuffer, 0, 40 + 4 * 256);
bitMapinfo = (BITMAPINFO *)bitBuffer;
bitMapinfo->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bitMapinfo->bmiHeader.biPlanes = 1;
for (int i = 0; i<256; i++)
{ //颜色的取值范围 (0-255)
bitMapinfo->bmiColors[i].rgbBlue = bitMapinfo->bmiColors[i].rgbGreen = bitMapinfo->bmiColors[i].rgbRed = (BYTE)i;
}
}
bitMapinfo->bmiHeader.biHeight = -img.rows;
bitMapinfo->bmiHeader.biWidth = img.cols;
bitMapinfo->bmiHeader.biBitCount = img.channels() * 8;
CRect drect;
pWnd->GetClientRect(drect); //pWnd指向CWnd类的一个指针
CClientDC dc(pWnd);
HDC hDC = dc.GetSafeHdc(); //HDC是Windows的一种数据类型,是设备描述句柄;
SetStretchBltMode(hDC, COLORONCOLOR);
StretchDIBits(hDC,
0,
0,
drect.right, //显示窗口宽度
drect.bottom, //显示窗口高度
0,
0,
img.cols, //图像宽度
img.rows, //图像高度
img.data,
bitMapinfo,
DIB_RGB_COLORS,
SRCCOPY
);
}
转自:https://jingyan.baidu.com/article/20b68a88b1dd7e796dec6241.html