Skip to content

Commit 1623965

Browse files
committed
增加python_opencv_tracking 实现调用摄像头从而抓住移动物体
1 parent 252daf7 commit 1623965

File tree

3 files changed

+86
-1
lines changed

3 files changed

+86
-1
lines changed

python_opencv_tracking/1.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
#coding:utf-8
2+
# 导入必要的软件包
3+
import argparse
4+
import datetime
5+
import imutils
6+
import time
7+
import cv2
8+
9+
# 创建参数解析器并解析参数
10+
ap = argparse.ArgumentParser()
11+
ap.add_argument("-v", "--video", help="path to the video file")
12+
ap.add_argument("-a", "--min-area", type=int, default=500, help="minimum area size")
13+
args = vars(ap.parse_args())
14+
15+
# 如果video参数为None,那么我们从摄像头读取数据
16+
if args.get("video", None) is None:
17+
camera = cv2.VideoCapture(0)
18+
time.sleep(0.25)
19+
20+
# 否则我们读取一个视频文件
21+
else:
22+
camera = cv2.VideoCapture(args["video"])
23+
24+
# 初始化视频流的第一帧
25+
firstFrame = None
26+
27+
# 遍历视频的每一帧
28+
while True:
29+
# 获取当前帧并初始化occupied/unoccupied文本
30+
(grabbed, frame) = camera.read()
31+
text = "Unoccupied"
32+
33+
# 如果不能抓取到一帧,说明我们到了视频的结尾
34+
if not grabbed:
35+
break
36+
37+
# 调整该帧的大小,转换为灰阶图像并且对其进行高斯模糊
38+
frame = imutils.resize(frame, width=500)
39+
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
40+
gray = cv2.GaussianBlur(gray, (21, 21), 0)
41+
42+
# 如果第一帧是None,对其进行初始化
43+
if firstFrame is None:
44+
firstFrame = gray
45+
continue
46+
# 计算当前帧和第一帧的不同
47+
frameDelta = cv2.absdiff(firstFrame, gray)
48+
thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
49+
50+
# 扩展阀值图像填充孔洞,然后找到阀值图像上的轮廓
51+
thresh = cv2.dilate(thresh, None, iterations=2)
52+
(cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
53+
cv2.CHAIN_APPROX_SIMPLE)
54+
55+
# 遍历轮廓
56+
for c in cnts:
57+
# if the contour is too small, ignore it
58+
if cv2.contourArea(c) < args["min_area"]:
59+
continue
60+
61+
# compute the bounding box for the contour, draw it on the frame,
62+
# and update the text
63+
# 计算轮廓的边界框,在当前帧中画出该框
64+
(x, y, w, h) = cv2.boundingRect(c)
65+
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
66+
text = "Occupied"
67+
# draw the text and timestamp on the frame
68+
# 在当前帧上写文字以及时间戳
69+
cv2.putText(frame, "Room Status: {}".format(text), (10, 20),
70+
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
71+
cv2.putText(frame, datetime.datetime.now().strftime("%A %d %B %Y %I:%M:%S%p"),
72+
(10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
73+
74+
# 显示当前帧并记录用户是否按下按键
75+
cv2.imshow("Security Feed", frame)
76+
cv2.imshow("Thresh", thresh)
77+
cv2.imshow("Frame Delta", frameDelta)
78+
key = cv2.waitKey(1) & 0xFF
79+
80+
# 如果q键被按下,跳出循环
81+
if key == ord("q"):
82+
break
83+
84+
# 清理摄像机资源并关闭打开的窗口
85+
camera.release()
86+
cv2.destroyAllWindows()
254 KB
Loading

test.txt

Lines changed: 0 additions & 1 deletion
This file was deleted.

0 commit comments

Comments
 (0)