opencv - 如何在python中读取窗口屏幕?
问题描述
我想读取窗口屏幕并使用该cv2.imshow()
方法显示它。
现在我正在截取窗口的屏幕截图并将其显示在 OpenCV 窗口上,但它也显示了我不想要的。
我应该采用哪种其他方法来获得我的结果?
这是我现在正在使用的代码。
while True:
img = screenshot()
img = np.array(img)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
cv2.imshow("Test", img)
我正在使用的库是:
- pyautogui # for Screenshot()
- cv2 # 用于 imshow()
- numpy # for array()
这是我不想发生的事情。 已保存的屏幕截图
https://i.stack.imgur.com/7PaC1.jpg
代码也在拍摄 imshow 窗口的屏幕截图,但我也不想关闭或最小化 imshow 窗口。
问:还有其他方法可以实现我想要的吗?
解决方案
我个人的偏好是使用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)
推荐阅读
- neo4j - 如何使用 URL 连接到 Neo4j?
- python - Python对某些数据应用低通滤波器
- java - 当一个任务引发异常时,如何让 ScheduledExecutorService 继续执行其他后续任务
- python - 创建 python 类时的强属性类型检查
- web-applications - manifest.json 如何忽略其范围内的特定文件夹?
- php - 第一次治疗后会话自动重置
- javascript - 使用客户端指纹编码 JWT 令牌?
- mongodb - Mongodb更新多个文档,如果不存在则插入
- mysql - 'AND columnName NOT IN' 在 mysql 中不起作用
- java - 如何通过命令行为 jfr 启用堆指标