首先我们要
导入pywin32,win32,opencv,cv
import cv2
import numpy as np
import win32gui
import win32ui
import win32con
获取图像
def grab_screen(region):
# 截取指定区域的图像
hwin = win32gui.GetDesktopWindow() # 获取桌面窗口的句柄
left, top, right, bottom = region # 解包区域的坐标值
width = right - left # 计算区域的宽度
height = bottom - top # 计算区域的高度
hwindc = win32gui.GetWindowDC(hwin) # 获取桌面窗口的设备上下文
srcdc = win32ui.CreateDCFromHandle(hwindc) # 从设备上下文创建一个兼容的 DC 对象
memdc = srcdc.CreateCompatibleDC() # 从源 DC 对象创建一个兼容的内存 DC 对象
bmp = win32ui.CreateBitmap() # 创建一个位图对象
bmp.CreateCompatibleBitmap(srcdc, width, height) # 从源 DC 对象创建一个兼容的位图
memdc.SelectObject(bmp) # 将位图对象选入内存 DC 对象
memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY) # 将源 DC 对象的指定区域复制到内存 DC 对象
signedIntsArray = bmp.GetBitmapBits(True) # 获取位图的像素数据
img = np.frombuffer(signedIntsArray, dtype='uint8') # 将像素数据转换为 NumPy 数组
img.shape = (height, width, 4) # 重新设置数组的形状,4 代表 RGBA 通道
srcdc.DeleteDC() # 删除源 DC 对象
memdc.DeleteDC() # 删除内存 DC 对象
win32gui.ReleaseDC(hwin, hwindc) # 释放桌面窗口的设备上下文
win32gui.DeleteObject(bmp.GetHandle()) # 删除位图对象
return cv2.cvtColor(img, cv2.COLOR_BGRA2BGR) # 将图像从 BGRA 格式转换为 BGR 格式,并返回
在获取图像后我们要找到我们的需要捕捉的窗口的当前位置
def get_window(windowname):
# 获取窗口句柄和坐标值
handle = win32gui.FindWindow(0, windowname) # 根据窗口名称查找窗口句柄
if handle == 0: # 如果没有找到窗口
print("Window not found") # 打印提示信息
return None # 返回空值
else: # 如果找到了窗口
return win32gui.GetWindowRect(handle), handle # 返回窗口的坐标值和句柄
之后对窗口置顶,避免报错
(x1, y1, x2, y2), handle = get_window(windowname)
win32gui.SendMessage(handle, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE, 0) # 向窗口发送还原最小化窗口的消息
win32gui.SetForegroundWindow(handle) # 将窗口设置为前台窗口
window_name = "TEST" # 定义显示图像的窗口的名称
(x1, y1, x2, y2), handle = get_window(windowname) # 调用 get_window 函数,获取 Anaconda Navigator 窗口的坐标值和句柄
# 截取窗口的图像
x3 = int(((size + 1) * x1 + (1 - size) * x2) // 2) # 计算截取区域的左上角横坐标 缩放后的
y3 = int(((size + 1) * y1 + (1 - size) * y2) // 2) # 计算截取区域的左上角纵坐标 缩放后的
x4 = int(((1 - size) * x1 + (size + 1) * x2) // 2) # 计算截取区域的右下角横坐标 缩放后的
y4 = int(((1 - size) * y1 + (size + 1) * y2) // 2) # 计算截取区域的右下角纵坐标 缩放后的 缩放比例为size 在config中定义
x5 = x4 - x3 # 计算截取区域的宽度
y5 = y4 - y3 # 计算截取区域的高度
list[0] = x3
list[1] = y3
list[2] = x4
list[3] = y4
list[4] = x5
list[5] = y5
然后获取窗口
img = grab_screen((list[0], list[1], list[2], list[3])) # 调用 grab_screen 函数,截取指定区域的图像
# 显示图像
cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) # 创建一个窗口,命名为 TEST
cv2.resizeWindow(window_name, list[4], list[5]) # 调整窗口的大小,与截取区域的大小一致
cv2.imshow(window_name, img) # 在窗口中显示图像