.h头文件
#pragma once
#include
#include
// 记住包含opencv目录
#include
// opencv_4.5.1 and contrib
#pragma comment(lib,“opencv_world454.lib”)
#pragma comment(lib,“opencv_world454d.lib”)
namespace _wss
{
/**
* 获取指定窗口句柄的mat
* @Param : h
*/
cv::Mat get_window_bits(HWND h);
/**
* 直接根据窗口进行截图
* @Param : name
* @Param : h
*/
cv::Mat screen_shot_by_window(std::string name);
cv::Mat screen_shot_by_window(HWND h);
}
.C源文件
#include “win32_screen_shots.h”
namespace _wss
{
cv::Mat get_window_bits(HWND h)
{
cv::Mat result;
HBITMAP bit = nullptr;
RECT rect{ 0 };
int width = 0, height = 0;
HDC hdc = nullptr, hdc_compatible = nullptr;
BITMAP info{ 0 };
int channels = 0;
if (h == nullptr)
return result;
do
{
if (GetWindowRect(h, &rect) == FALSE)
break;
if (rect.left < 0)
rect.left = 0;
if (rect.top < 0)
rect.top = 0;
width = rect.right - rect.left;
height = rect.bottom - rect.top;
hdc = GetWindowDC(h);
if (hdc == nullptr)
break;
hdc_compatible = CreateCompatibleDC(hdc);
if (hdc_compatible == nullptr)
break;
bit = CreateCompatibleBitmap(hdc, width, height);
if (bit == nullptr)
break;
SelectObject(hdc_compatible, bit);
if (BitBlt(hdc_compatible, 0, 0, width, height, hdc, 0, 0, SRCCOPY) == FALSE)
break;
if (GetObjectA(bit, sizeof(BITMAP), &info) == 0)
break;
channels = info.bmBitsPixel == 1 ? 1 : info.bmBitsPixel / 8;
result.create(cv::Size(info.bmWidth, info.bmHeight), CV_MAKETYPE(CV_8U, channels));
if (GetBitmapBits(bit, info.bmHeight * info.bmWidth * channels, result.data) == 0)
break;
} while (false);
if (hdc)
ReleaseDC(h, hdc);
if (hdc_compatible)
DeleteDC(hdc_compatible);
if (bit)
DeleteObject(bit);
return result;
}
cv::Mat screen_shot_by_window(HWND h)
{
while (1)
{
return get_window_bits(h);
}
}
cv::Mat screen_shot_by_window(std::string name)
{
while (1)
{
return get_window_bits(FindWindowA(0, name.c_str()));
}
}
}
测试文件
while (1)
{
cv::Mat src = _wss::screen_shot_by_window(GetDesktopWindow());
cv::waitKey(1);
imwrite("D:/opencv/tu/小人.png", src);
Mat dst = imread("D:/opencv/tu/小人.png");
imshow("result", dst);
}