opencv screenshots refer to this article: https://blog.csdn.net/qq_18984151/article/details/79231953
opencv record screen:
#include <iostream>
#include<opencv2/opencv.hpp>
#include <windows.h>
using namespace cv;
using namespace std;
HBITMAP hBmp;
HBITMAP hOld;
/*********************************************************************************/
//抓取当前屏幕的三个函数Screen(),HBitmapToMat(HBITMAP& _hBmp, Mat& _mat),printScreen()
void Screen() {
//创建画板
HDC hScreen = CreateDC("DISPLAY", NULL, NULL, NULL);
HDC hCompDC = CreateCompatibleDC(hScreen);
//取屏幕宽度和高度
int nWidth = GetSystemMetrics(SM_CXSCREEN);
int nHeight = GetSystemMetrics(SM_CYSCREEN);
//创建Bitmap对象
hBmp = CreateCompatibleBitmap(hScreen, nWidth, nHeight);
hOld = (HBITMAP)SelectObject(hCompDC, hBmp);
BitBlt(hCompDC, 0, 0, nWidth, nHeight, hScreen, 0, 0, SRCCOPY);
SelectObject(hCompDC, hOld);
//释放对象
DeleteDC(hScreen);
DeleteDC(hCompDC);
}
//把HBITMAP型转成Mat型
BOOL HBitmapToMat(HBITMAP& _hBmp, Mat& _mat)
{
//BITMAP操作
BITMAP bmp;
GetObject(_hBmp, sizeof(BITMAP), &bmp);
int nChannels = bmp.bmBitsPixel == 1 ? 1 : bmp.bmBitsPixel / 8;
int depth = bmp.bmBitsPixel == 1 ? IPL_DEPTH_1U : IPL_DEPTH_8U;
//mat操作
Mat v_mat;
v_mat.create(cvSize(bmp.bmWidth, bmp.bmHeight), CV_MAKETYPE(CV_8U, nChannels));
GetBitmapBits(_hBmp, bmp.bmHeight*bmp.bmWidth*nChannels, v_mat.data);
_mat = v_mat;
return TRUE;
}
void printScreen()
{
int rate = 27;
VideoWriter writer("1_1.avi", CV_FOURCC('M', 'J', 'P', 'G'), 5, Size(1960, 1080));
Mat src;
Mat dst;
int i = 0;
//录制时间
while (i < 100) {
//屏幕截图
Screen();
//类型转换
HBitmapToMat(hBmp, src);
//调整大小
resize(src, dst, cvSize(1960, 1080), 0, 0);
imshow("dst", dst);
writer << dst;
DeleteObject(hBmp);
waitKey(rate);//这里调节帧数 现在27ms是1000/27帧
i++;
}
}
/******************************************************************************************************/
int main() {
printScreen();
return 0;
}
VideoWriter is written into the video type, VideoWriter writer ( "1_1.avi", CV_FOURCC ( 'M', 'J', 'P', 'G'), 5, Size (1960, 1080));
The main parameters are: file path (empty overwritten, not appended), video type, frame rate, window size (the size of the picture must be the same).
The program automatically shut itself must be forced to close the resulting video will not play