方法一 使用 PIL 库实现
from PIL import ImageGrab
import cv2
import numpy as np
while True:
# 获取屏幕截图
screenshot = ImageGrab.grab()
screenshot_cv = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
if cv2.getWindowProperty('test', cv2.WND_PROP_VISIBLE) < 1:
cv2.imshow('test', screenshot_cv)
else:
cv2.imshow('test', screenshot_cv)
key = cv2.waitKey(1)
if key == 27:
break
cv2.destroyAllWindows()
方法一 使用 pyautogui 库实现
import pyautogui
import cv2
import numpy as np
# 屏幕区域 如需要全屏就不加这个参数
screen = (0, 0, 300, 300)
while True:
screenshot = pyautogui.screenshot(region=screen)
screenshot_cv = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
# 检测窗口是否存在,存在就更新窗口内容,否则就创建新窗口
if cv2.getWindowProperty('test', cv2.WND_PROP_VISIBLE) < 1:
cv2.imshow('test', screenshot_cv)
else:
cv2.imshow('test', screenshot_cv)
key = cv2.waitKey(1)
if key == 27:
break
cv2.destroyAllWindows()