前言
为了方便opencv进行fps游戏指针附近目标检测,需要降低截图延迟。自带PIL库的ImageGrab功能速度较慢,这里尝试使用C实现截图后用python调用动态链接库的方法尝试加速,最后实测可快5倍左右,用时与python的mss库相近(该库也是调用c链接库实现)
一、动态链接库编写
1. C实现截图功能
目标是实现以指针为中心,截图桌面一个width*height的区域,我一般截图640*640
#include <windows.h>
#include <stdio.h>
extern "C" {
__declspec(dllexport) void CaptureDesktop(int width, int height, unsigned char* buffer) {
POINT my_cursor;
int centerX, centerY;
GetCursorPos(&my_cursor);
centerX = my_cursor.x;
centerY = my_cursor.y;
//
// 获取屏幕设备上下文
HDC hScreenDC = GetDC(NULL);
// 创建内存设备上下文
HDC hMemoryDC = CreateCompatibleDC(hScreenDC);
// 确保截图区域在屏幕范围内
int left = centerX - (width / 2);