[Python] 纯文本查看 复制代码
import cv2
import numpy as np
import pyautogui
# 初始化背景帧
while True:
# 背景图
background = pyautogui.screenshot()
background = cv2.cvtColor(np.array(background), cv2.COLOR_RGB2BGR)
background = cv2.cvtColor(background, cv2.COLOR_BGR2GRAY)
# 下一帧图像
screenshot = pyautogui.screenshot()
frame = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 计算帧差
diff = cv2.absdiff(background, gray_frame)
# 阈值处理
_, thresh = cv2.threshold(diff, 30, 255, cv2.THRESH_BINARY)
# 形态学处理
kernel = np.ones((5, 5), np.uint8)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
# 查找轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('Frame', frame)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
cv2.destroyAllWindows()
|