#导入Pandas库
import Pandas as panda
# 导入OpenCV库
import cv2
#导入时间模块
import time
#从datetime 模块导入datetime 函数
from datetime import datetime
# 对于初始帧,以变量initialState的形式将初始状态指定为None
initialState = None
# 帧中检测到任何运动时存储所有轨迹的列表
motionTrackList= [ None, None ]
# 一个新的“时间”列表,用于存储检测到移动时的时间
motionTime = []
# 使用带有初始列和最终列的Panda库初始化数据帧变量“DataFrame”
dataFrame = panda.DataFrame(columns = ["Initial", "Final"])
# 使用cv2模块启动网络摄像头以捕获视频
video = cv2.VideoCapture(0)
# 使用无限循环从视频中捕获帧
while True:
# 使用read功能从视频中读取每个图像或帧
check, cur_frame = video.read()
#将'motion'变量定义为等于零的初始帧
var_motion = 0
# 从彩色图像创建灰色帧
gray_image = cv2.cvtColor(cur_frame, cv2.COLOR_BGR2GRAY)
# 从灰度图像中使用GaussianBlur函数找到变化部分
gray_frame = cv2.GaussianBlur(gray_image, (21, 21), 0)
# 在第一次迭代时进行条件检查
# 如果为None,则把grayFrame赋值给变量initalState
if initialState is None:
initialState = gray_frame
continue
# 计算静态(或初始)帧与我们创建的灰色帧之间的差异
differ_frame = cv2.absdiff(initialState, gray_frame)
# 静态或初始背景与当前灰色帧之间的变化将突出显示
thresh_frame = cv2.threshold(differ_frame, 30, 255, cv2.THRESH_BINARY)[1]
thresh_frame = cv2.dilate(thresh_frame, None, iterations = 2)
#对于帧中的移动对象,查找轮廓
cont,_ = cv2.findContours(thresh_frame.copy(),
cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cur in cont:
if cv2.contourArea(cur) < 10000:
continue
var_motion = 1
(cur_x, cur_y,cur_w, cur_h) = cv2.boundingRect(cur)
# 在移动对象周围创建一个绿色矩形
cv2.rectangle(cur_frame, (cur_x, cur_y), (cur_x + cur_w, cur_y + cur_h), (0, 255, 0), 3)
# 从帧中添加运动状态
motionTrackList.append(var_motion)
motionTrackList = motionTrackList[-2:]
# 添加运动的开始时间
if motionTrackList[-1] == 1 and motionTrackList[-2] == 0:
motionTime.append(datetime.now())
# 添加运动的结束时间
if motionTrackList[-1] == 0 and motionTrackList[-2] == 1:
motionTime.append(datetime.now())
# 在显示捕获图像的灰度级中
cv2.imshow("The image captured in the Gray Frame is shown below: ", gray_frame)
# 显示初始静态帧和当前帧之间的差异
cv2.imshow("Difference between the inital static frame and the current frame: ", differ_frame)
# 在框架屏幕上显示视频中的黑白图像
cv2.imshow("Threshold Frame created from the PC or Laptop Webcam is: ", thresh_frame)
#通过彩色框显示物体的轮廓
cv2.imshow("From the PC or Laptop webcam, this is one example of the Colour Frame:", cur_frame)
# 创建处于等待状态的键盘按键
wait_key = cv2.waitKey(1)
# 借助'm'键结束我们系统的整个进行
if wait_key == ord('m'):
# 当屏幕上有物体运行时把运动变量值添加到列表motiontime中
if var_motion == 1:
motionTime.append(datetime.now())
break
# 最后,我们在数据帧中添加运动时间
for a in range(0, len(motionTime), 2):
dataFrame = dataFrame.append({"Initial" : time[a], "Final" : motionTime[a + 1]}, ignore_index = True)
# 记录下所有运行,并创建到一个CSV文件中
dataFrame.to_csv("EachMovement.csv")
# 释放视频内存
video.release()
#现在,在openCV的帮助下关闭或销毁所有打开的窗口
cv2.destroyAllWindows()