python windows 指定窗口截图

  1. 禁用windows的缩放,使用 100% 比例的缩放
  2. 图片的返回格式为 PIL.image
  3. 截图的瞬间会暂时将被截图的窗口置于桌面顶层。如果要持续的截图,应始终保持焦点在对应窗口上,鼠标点击了其他窗口或者最小化了当前窗口,就会被迫终止掉。
# use 'pip install pywin32' to install
import win32api, win32con, win32gui 
from PIL import Image, ImageGrab

主要函数有两个,通过调用后一个fetch_image()来获取屏幕截图

def get_window_pos(name):
    name = name
    handle = win32gui.FindWindow(0, name)
    # 获取窗口句柄
    if handle == 0:
        return None
    else:
        # 返回坐标值和handle
        return win32gui.GetWindowRect(handle), handle


def fetch_image():
    (x1, y1, x2, y2), handle = get_window_pos('Euro Truck Simulator 2(换上你的窗口名!)')
    # 发送还原最小化窗口的信息
    win32gui.SendMessage(handle, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE, 0)
    # 设为高亮
    win32gui.SetForegroundWindow(handle)
    # 截图
    grab_image = ImageGrab.grab((x1, y1, x2, y2))
    
    return grab_image

最后,如果要在cv2和PIL的图片格式之间做转换
可以参考某dalao的这篇blog

https://blog.csdn.net/qq_38153833/article/details/88060268

你可能感兴趣的:(python)