31 lines
704 B
Python
31 lines
704 B
Python
|
|
import cv2
|
||
|
|
import numpy as np
|
||
|
|
|
||
|
|
# 创建背景建模器 (MOG2)
|
||
|
|
bg_subtractor = cv2.createBackgroundSubtractorMOG2(history=500, varThreshold=16, detectShadows=True)
|
||
|
|
|
||
|
|
cap = cv2.VideoCapture("your_video.mp4") # 或者用图片序列
|
||
|
|
|
||
|
|
while True:
|
||
|
|
ret, frame = cap.read()
|
||
|
|
if not ret:
|
||
|
|
break
|
||
|
|
|
||
|
|
# 应用背景建模器
|
||
|
|
fg_mask = bg_subtractor.apply(frame)
|
||
|
|
|
||
|
|
# 获取背景图像
|
||
|
|
bg_image = bg_subtractor.getBackgroundImage()
|
||
|
|
|
||
|
|
# 显示
|
||
|
|
cv2.imshow("Frame", frame)
|
||
|
|
cv2.imshow("Foreground Mask", fg_mask)
|
||
|
|
if bg_image is not None:
|
||
|
|
cv2.imshow("Background Model", bg_image)
|
||
|
|
|
||
|
|
if cv2.waitKey(30) & 0xFF == 27:
|
||
|
|
break
|
||
|
|
|
||
|
|
cap.release()
|
||
|
|
cv2.destroyAllWindows()
|