说明
使用pyautogui方法实现截屏;代码
import pyautoguiimport cv2import numpy as np# 下面的数字分别代表:左上角横向坐标,左上角纵向坐标,截取图像的宽度,截取图像的高度;img = pyautogui.screenshot(region=[0, 0, 1902, 1080])# 将获取的图像转换成二维矩阵形式,然后再将RGB转成BGR# 因为`imshow`默认通道顺序是`BGR`,而`pyautogui`默认是`RGB`所以要转换一下img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)cv2.imshow("截屏", img)cv2.waitKey(0)注释
此方法不能指定获取指定程序的窗口,因此窗口也不能被遮挡; 【2】说明
使用win32gui方法实现截屏;代码
《1》
获取目标程序窗口的句柄和标题;打印所有窗口的hwnd和title;根据窗口句柄就可以进行指定截图了; import win32gui# 创建字典保存窗口的句柄与名称映射关系hwnd_title = dict()def get_all_hwnd(hwnd, mouse):if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):hwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)})win32gui.EnumWindows(get_all_hwnd, 0)for h, t in hwnd_title.items():if t != "":print(h, t) import win32gui# GetDesktopWindow 获得代表整个屏幕的一个窗口(桌面窗口)句柄hd = win32gui.GetDesktopWindow()# 获取所有子窗口hwndChildList = []win32gui.EnumChildWindows(hd, lambda hwnd, param: param.append(hwnd), hwndChildList)for hwnd in hwndChildList:print("句柄:", hwnd, "标题:", win32gui.GetWindowText(hwnd))# f.write("句柄:" + str(hwnd) + " 标题:" + win32gui.GetWindowText(hwnd) + '\n')结果
3802250 mouseControle – OpenCVDemo.py3278598 此电脑《2》
使用PyQt5进行全屏的截取操作;如果想截取特定的窗口,只需要将C:/Windows/system32/cmd.exe换成上一个程序中打印的title,并且保证那个窗口没有被你最小化即可;代码
import sysimport win32guifrom PyQt5.QtWidgets import QApplication# 这个是全屏窗口hwnd = win32gui.FindWindow(None, 'C:/Windows/system32/cmd.exe')# 这个是指定程序# hwnd = win32gui.FindWindow(None, win32gui.GetWindowText(3212524))app = QApplication(sys.argv)screen = QApplication.primaryScreen()img = screen.grabWindow(hwnd).toImage()img.save(r"C:\Users\SUNxRUN\Desktop\screenshot.jpg")# 前置窗口 win32gui.SetForegroundWindow(hwnd)《3》
暂时废弃;实时使用win32gui截屏用Mat格式显示的核心程序;代码
import win32guiimport cv2import numpy as npfrom PIL import ImageGrab # 操作图像hwnd = win32gui.FindWindow(None, 'QQMail - Inbox - 360极速浏览器X 21.0')#第二个参数需要用二、a、那个程序运行来获得while True:x_start, y_start, x_end, y_end = win32gui.GetWindowRect(hwnd)# 坐标信息box = (x_start, y_start, x_end, y_end)image = ImageGrab.grab(box)img=cv2.cvtColor(np.asarray(image),cv2.COLOR_RGB2BGR)cv2.imshow('Img',img)cv2.waitKey(1)