import cv2
import time
import datetime
import os
import easygui
def mkdir(path):
folder = os.path.exists(path)
if not folder:
os.makedirs(path)
print
("--- new folder... ---")
print
("--- OK ---")
else:
print
("--- There is this folder! ---")
file = "D:\\CCTVlook"
mkdir(file)
print("文件储存于D:\\CCTVlook")
camera = cv2.VideoCapture(0)
title = easygui.msgbox(msg="将于5s后开始记录摄像头移动情况!""\n""请离开保证背景稳定""\n"
, title="运动检测追踪拍照", ok_button="开始执行")
msg = easygui.msgbox(msg="移动物体保存于D:\\CCTVlook")
time.sleep(5)
background = None
def nothing(x):
pass
cv2.namedWindow("fps")
cv2.createTrackbar('level', 'fps', 21, 255, nothing)
shot_idx = 0
while True:
text = "No Target"
flat = 0
kerne = cv2.getTrackbarPos('level', 'fps')
if kerne % 2 == 0:
kerne = kerne + 1
(grabbed, frame) = camera.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (kerne, kerne), 0)
if background is None:
background = gray
continue
frameDelta = cv2.absdiff(background, gray)
thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)[-2]
for c in cnts:
if cv2.contourArea(c) < 1800:
continue
flat = 1
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
text = "Find Target! save as D:\CCTVlook"
print("Find Target!")
cv2.putText(frame, text, (10, 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
cv2.putText(frame, datetime.datetime.now().strftime("%A %d %B %Y %I:%M:%S%p"),
(10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
cv2.imshow("fps", frame)
key = cv2.waitKey(1) & 0xFF
ch = cv2.waitKey(1)
if key == ord("q"):
break
if flat == 1:
fn = 'D:\CCTVlook\shot%d.jpg' % (shot_idx)
cv2.imwrite(fn, frame)
shot_idx += 1
continue
camera.release()
cv2.destroyAllWindows()