简体   繁体   English

为什么特定窗口的 PIL.ImageGrab.grab 无法正常工作?

[英]Why does PIL.ImageGrab.grab of specific window doesn't work properly?

I am trying to capture specific windows, and displaying them using ImageGrab using the following code:我正在尝试捕获特定窗口,并使用以下代码使用ImageGrab显示它们:

import cv2
import numpy as np
from PIL import ImageGrab
import pygetwindow
import pyautogui

titles = pygetwindow.getAllTitles()

while(1):
    cars = pygetwindow.getWindowsWithTitle('car - Google Search - Google Chrome')[0]
    print(cars.left, cars.top ,cars.width, cars.height)
    img = ImageGrab.grab(bbox=(int(cars.left),int(cars.top),cars.width,cars.height)) #x, y, w, h
    img_np = np.array(img)
    frame = cv2.cvtColor(img_np, cv2.CV_8U)
    cv2.waitKey(1)
    cv2.imshow("frame", frame)
cv2.destroyAllWindows()

It is somehow able to display Chrome, and able to follow the window, but I noticed that whether the x and y axis of the bbox is larger than the width and height, there will be an error.它以某种方式能够显示Chrome,并且能够跟随窗口,但是我注意到bboxxy轴是否大于宽度和高度,会出现错误。 Furthermore, whenever I try to move the Chrome browser around, the frame's height and width key adjust itself.此外,每当我尝试移动 Chrome 浏览器时,框架的高度和宽度键都会自行调整。 Any ideas on how to solve these issues?关于如何解决这些问题的任何想法?

The problem originates from your ImageGrab.grab call.问题源于您的ImageGrab.grab调用。 Unfortunately, it's not mentioned in the documentation itself, but from the source code , you see, that it's:不幸的是,文档本身并没有提到它,但是从源代码中可以看到,它是:

ImageGrab.grab(bbox=(left, top, right, bottom))

So, you must calculate right and bottom accordingly.因此,您必须相应地计算rightbottom This code works perfectly fine for me:这段代码对我来说非常好:

import cv2
import numpy as np
from PIL import ImageGrab
import pygetwindow

titles = pygetwindow.getAllTitles()

while True:
    cars = pygetwindow.getWindowsWithTitle('car - Google Search - Google Chrome')[0]
    print(cars.left, cars.top, cars.width, cars.height)
    img = ImageGrab.grab(bbox=(int(cars.left),
                               int(cars.top),
                               int(cars.left + cars.width),
                               int(cars.top + cars.height)))
    frame = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
    cv2.waitKey(1)
    cv2.imshow('frame', frame)

Please notice, I also corrected your cv2.cvtColor call, such that proper colors are displayed.请注意,我还更正了您的cv2.cvtColor调用,以便显示正确的颜色。

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.19041-SP0
Python:        3.9.1
PyCharm:       2021.1.3
NumPy:         1.20.3
OpenCV:        4.5.2
Pillow:        8.3.0
pygetwindow:   0.0.9
----------------------------------------

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM