
import cv2
import time
import datetime
import os
def mkdir(path):
folder = os.path.exists(path)
if not folder: # 判斷是否存在文件夾如果不存在則創建為文件夾
os.makedirs(path) # makedirs 創建文件時如果路徑不存在會創建這個路徑
print
("--- new folder... ---")
print
("--- OK ---")
else:
print
("--- There is this folder! ---")
file = "D:\\CCTVlook" # 保存位置
mkdir(file)
print("文件儲存於D:\\CCTVlook")
# 選取攝像頭,0為筆記本內置的攝像頭,1,2···為外接的攝像頭
camera = cv2.VideoCapture(0)
time.sleep(5) # 延遲5s執行
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 # 設置一個標簽,當有運動的時候為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("Frame Delta", frameDelta)
cv2.imshow("fps", frame)
# cv2.imshow("Thresh", thresh)
key = cv2.waitKey(1) & 0xFF
# 如果q鍵被按下,跳出循環
ch = cv2.waitKey(1)
if key == ord("q"):
break
if flat == 1: # 設置一個標簽,當有運動的時候為1
fn = "D:\CCTVlook\shot%d.jpg" % (shot_idx)
cv2.imwrite(fn, frame)
shot_idx += 1
continue
原文:https://blog.csdn.net/dgut_guangdian/article/details/79762409
