我正在尝试捕获特定的窗口,并使用以下代码使用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()
它在某种程度上能够显示Chrome,并且能够跟随窗口,但我注意到bbox
的x
和y
轴是否大于宽度和高度,都会出现错误。此外,每当我试图移动Chrome浏览器时,框架的高度和宽度关键点都会自行调整。关于如何解决这些问题有什么想法吗?
问题源于您的ImageGrab.grab
调用。不幸的是,文档中没有提到它,但从源代码中可以看出,它是:
ImageGrab.grab(bbox=(left, top, right, bottom))
因此,必须相应地计算right
和bottom
。这个代码对我来说非常好:
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)
请注意,我还更正了您的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
----------------------------------------