Thursday, May 13, 2010

Screen Grabbing with OpenCV

Note: this uses only the highgui.h header, since I'm not using any OpenCV functions.

Code

#define WIN32_LEAN_AND_MEAN
#include
#include
#include

#include


class ScreenShot
{
protected:
HWND hDesktopWnd;
HDC hDesktopDC, hCaptureDC;
BITMAPINFO bmInfo;

public:
int nScreenWidth, nScreenHeight;
HBITMAP hCaptureBitmap;

void init ()
{

nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
nScreenHeight = GetSystemMetrics(SM_CYSCREEN);

hDesktopWnd = GetDesktopWindow();
hDesktopDC = GetDC(hDesktopWnd);

int padding = 0;
while ( (nScreenWidth*3 + padding)%4 != 0)
padding++;

bmInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmInfo.bmiHeader.biWidth = nScreenWidth;
bmInfo.bmiHeader.biHeight = nScreenHeight;
bmInfo.bmiHeader.biPlanes = 1;
bmInfo.bmiHeader.biBitCount = 24;
bmInfo.bmiHeader.biCompression = 0;
bmInfo.bmiHeader.biSizeImage = nScreenHeight * (nScreenWidth * 3 + padding);
bmInfo.bmiHeader.biXPelsPerMeter = 0;
bmInfo.bmiHeader.biYPelsPerMeter = 0;
bmInfo.bmiHeader.biClrUsed = 0;
bmInfo.bmiHeader.biClrImportant = 0;


}

void captureScreen()
{

hCaptureDC = CreateCompatibleDC(hDesktopDC);
hCaptureBitmap = CreateCompatibleBitmap(hDesktopDC, nScreenWidth, nScreenHeight);
SelectObject(hCaptureDC, hCaptureBitmap);
BitBlt(hCaptureDC, 0, 0, nScreenWidth, nScreenHeight, hDesktopDC, 0, 0, SRCCOPY);

}

void hBitMap2IplImage (IplImage *img)
{

GetDIBits(hCaptureDC, hCaptureBitmap, 0, nScreenHeight, img->imageData, &bmInfo, DIB_RGB_COLORS);

}

void close ()
{

ReleaseDC(hDesktopWnd, hDesktopDC);
DeleteDC(hCaptureDC);
DeleteObject(hCaptureBitmap);

}

};


I noticed that I had to close and init for each frame grad while using this code.
I'm new to Windows programming and not really keen to learn it, but I'd welcome if anyone can tell me how to optimize this code, especially how to avoid closing and initializing all the variables.

1 comment:

My Mind said...

I noticed that I had to close and init for each frame grad while using this code.
I'm new to Windows programming and not really keen to learn it, but I'd welcome if anyone can tell me how to optimize this code, especially how to avoid closing and initializing all the variables.