Python 中的 WebCam 运动检测器程序?
pythonserver side programmingprogramming
在此我们将编写 Python 程序,该程序将分析从网络摄像头拍摄的图像并尝试检测运动并将网络摄像头视频的时间间隔存储在 csv 文件中。
所需库
我们将为此使用 OpenCV 和 pandas 库。如果尚未安装,您可以使用 pip 安装它,如下所示:
$pip install opencv2, pandas
示例代码
#导入所需库 import cv2 import pandas as pd import time from datetime import datetime #初始化变量 stillImage = None motionImage = [ None, None ] time = [] #使用开始和结束时间初始化 DataFrame df = pd.DataFrame(columns = ["start", "end"]) #捕获视频 video = cv2.VideoCapture(0) while True: #开始从视频中读取图像 check, frame = video.read() motion = 0 #将彩色图像转换为灰度图像 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (21, 21), 0) if stillImage is None: stillImage = gray continue # 静态图像和当前图像。 diff_frame = cv2.absdiff(stillImage, gray) # 如果静态背景和当前帧大于 25,则将图像更改为白色。 thresh_frame = cv2.threshold(diff_frame, 25, 255, cv2.THRESH_BINARY)[1] thresh_frame = cv2.dilate(thresh_frame, None, iterations = 2) # 从移动物体中查找轮廓和层次结构。 contours,hierachy = cv2.findContours(thresh_frame.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: if cv2.contourArea(contour) < 10000: continue motion = 1 (x, y, w, h) = cv2.boundingRect(contour) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3) # 附加运动的当前状态 motionImage.append(motion) motionImage = motionImage[-2:] # 附加运动的开始时间 if motionImage[-1] == 1 且 motionImage[-2] == 0: time.append(datetime.now()) # 附加运动结束时间 if motionImage[-1] == 0 且 motionImage[-2] == 1: time.append(datetime.now()) # 以灰度显示图像 cv2.imshow("Gray_Frame", gray) # 显示黑白帧 & 如果强度差大于 25,则变为白色 cv2.imshow("Threshold Frame", thresh_frame) # 显示彩色帧 cv2.imshow("Colored_Frame", frame) key = cv2.waitKey(1) # 按 q 停止该过程 if key == ord('q'): if motion == 1: time.append(datetime.now()) break # 附加运动时间 for i in range(0, len(time), 2): df = df.append({"Start":time[i], "End":time[i + 1]}, ignore_index = True) # 创建一个将保存运动时间的 csv 文件 df.to_csv("FrameInMotion_time.csv") video.release() # 关闭窗口 cv2.destroyAllWindows()
输出
我们可以看到我们将获得 3 个不同的窗口,它们将以三种不同的模式(灰度、彩色和黑白)显示我们当前的网络摄像头运动。
它还将把我们的网络摄像头运动的日期时间存储在 csv 中,我们从 csv 输出的内容将类似于:
FrameMotion_time.csv(输出)
start end End Start 0 2019-02-21 18:10:59.718005 2019-02-21 18:08:35.791487