首页 > 解决方案 > 如何在python中读取窗口屏幕?

问题描述

我想读取窗口屏幕并使用该cv2.imshow()方法显示它。

现在我正在截取窗口的屏幕截图并将其显示在 OpenCV 窗口上,但它也显示了我不想要的。

我应该采用哪种其他方法来获得我的结果?

这是我现在正在使用的代码。

while True:
    img = screenshot()
    img = np.array(img)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    cv2.imshow("Test", img)

我正在使用的库是:

  1. pyautogui # for Screenshot()
  2. cv2 # 用于 imshow()
  3. numpy # for array()

这是我不想发生的事情。 已保存的屏幕截图

https://i.stack.imgur.com/7PaC1.jpg

代码也在拍摄 imshow 窗口的屏幕截图,但我也不想关闭或最小化 imshow 窗口。

问:还有其他方法可以实现我想要的吗?

标签: opencvpyautogui

解决方案


我个人的偏好是使用cv2.imwrite而不是cv2.imshow. 但是如果您需要使用 imshow,您可以查看这两种方法,看看哪种方法适合您的要求

选项 1:在截取屏幕截图之前销毁窗口,然后重新制作,代码如下所示:

while True:
    img = screenshot()
    img = np.array(img)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    cv2.imshow("Test", img)
    cv2.destroyAllWindows()

我个人认为这种方法没有什么好处,因为它主要只是继续创建和销毁窗口

选项 2:OpenCV 还允许您移动窗口,您可以在要截屏之前使用它来移动窗口,然后再将其移回。相同的代码如下所示:

while True:
    # Just to check if img exists or not, needed for the 1st run of the loop
    if 'img' in locals():
        cv2.waitKey(100) #Without the delay, the imshow window will only keep flickering
        cv2.moveWindow("Test", height, width)

    img = screenshot()
    img = np.array(img)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    
    height, width, ch = img.shape

    cv2.imshow("Test", img)
    cv2.moveWindow("Test", 0, 0)

以上 2 个选项使用的是您已经在代码中使用的库。还有第三个选项,您可以在其中最小化窗口,然后在每次截屏时重新打开它。你可以在这里这里找到对它的引用。同样的代码应该是这样的。

import ctypes
import win32gui


while True:
    # Just to check if img exists or not, 
    # needed for the 1st run of the loop
    if 'img' in locals():
        cv2.waitKey(500) # Delay to stop the program from constantly opening and closing the window after itself
        ctypes.windll.user32.ShowWindow(hwnd, 7)

    # Window needs some time to be minimised
    cv2.waitKey(500)
    img = pyautogui.screenshot()

    img = np.array(img)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        
    cv2.imshow("Test", img)

    hwnd = win32gui.GetForegroundWindow()
    ctypes.windll.user32.ShowWindow(hwnd, 9)

推荐阅读