opencv2 mat不用imshow直接显示在窗口中 支持多线程
使用opencv2桌面应用程序的时候,在单独线程里开opencv 摄像头的时候发现直接imshow就卡了,imshow窗口没有一点反应,但获取帧的循环可以打印出调试信息。说明opencv打开摄像头是可用的,并获取了摄像头数据。于是转码用BitBlt实现显示在窗口中。
#include <opencv2/opencv.hpp>
using namespace cv;
HWND hWin;
HDC hdcScreen, hdcMemDC;
char* lpbitmap;
HBITMAP hbmScreen;
BITMAPINFO bi;
int lineBytes;
int bmpSize;
UINT width, height;
void CameraProcessFunc(void)
{
//打开视频文件:其实就是建立一个VideoCapture结构
VideoCapture video(0);
//检测是否正常打开:成功打开时,isOpened返回ture
if (!video.isOpened())
{
return;
}
//检测视频的大小
Size videoSize = Size((int)video.get(CAP_PROP_FRAME_WIDTH), (int)video.get(CAP_PROP_FRAME_HEIGHT));
width = videoSize.width;
height = videoSize.height;
hdcScreen = GetDC(hWnd);
hdcMemDC = CreateCompatibleDC(hdcScreen);
hbmScreen = CreateCompatibleBitmap(hdcScreen, width, height);
SelectObject(hdcMemDC, hbmScreen);
bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
bi.bmiHeader.biWidth = width;
bi.bmiHeader.biHeight = height;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biBitCount = 24;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biSizeImage = 0;
bi.bmiHeader.biXPelsPerMeter = 0;
bi.bmiHeader.biYPelsPerMeter = 0;
bi.bmiHeader.biClrUsed = 0;
bi.bmiHeader.biClrImportant = 0;
lineBytes = ((width * bi.bmiHeader.biBitCount + 31) / 32) * 4;
bmpSize = lineBytes * height;
//lpbitmap = new char[bmpSize];
lpbitmap = (char*)malloc(bmpSize);
Mat videoFrame;
while (1)
{
video >> videoFrame;
if (videoFrame.empty())
{
break;
}
for (int i = 0; i < height; i++)
{
int destIndex = (height - i - 1) * lineBytes;
int srcIndex = i * width * 3;
memcpy(&lpbitmap[destIndex] , &(videoFrame.data[srcIndex]), width * 3);
}
SetDIBits(hdcMemDC, hbmScreen, 0, height, lpbitmap, &bi, DIB_RGB_COLORS);
BitBlt(hdcScreen, 0, 0, width, height, hdcMemDC, 0, 0, SRCCOPY);
Sleep(100);
}
}