一、概念運(yùn)動(dòng)偵測(cè),英文翻譯為“Motion detection technology”,一般也叫移動(dòng)檢測(cè),常用于無(wú)人值守監(jiān)控錄像和自動(dòng)報(bào)警。通過(guò)攝像頭按照不同幀率采集得到的圖像會(huì)被CPU按照一定算法進(jìn)行計(jì)算和比較,當(dāng)畫(huà)面有變化時(shí),如有人走過(guò),鏡頭被移動(dòng),計(jì)算比較結(jié)果得出的數(shù)字會(huì)超過(guò)閾值并指示系統(tǒng)能自動(dòng)作出相應(yīng)的處理。 差分算法 差分檢測(cè)根據(jù)當(dāng)前圖像與參考圖像的差別分析來(lái)判斷序列圖像中是否有運(yùn)動(dòng)的物體。在環(huán)境亮度變化不大的情況下,如果對(duì)應(yīng)像素灰度值的差異小于某個(gè)閾值,則認(rèn)為畫(huà)面靜止無(wú)運(yùn)動(dòng)變化,如果圖像區(qū)域某處的灰度變化大于某個(gè)閾值,則認(rèn)為這是由于圖像中運(yùn)動(dòng) 的物體所引起的,然后求出運(yùn)動(dòng)目標(biāo)在圖像中的位置。 基于相鄰幀差的算法: 將前后兩幀圖像對(duì)應(yīng)像素點(diǎn)的灰度值相減; 一、幀差法1. 幀差法原理 移動(dòng)偵測(cè)即是根據(jù)視頻每幀或者幾幀之間像素的差異,對(duì)差異值設(shè)置閾值,篩選大于閾值的像素點(diǎn),做掩模圖即可選出視頻中存在變化的楨。幀差法較為簡(jiǎn)單的視頻中物體移動(dòng)偵測(cè),幀差法分為:?jiǎn)螏睢蓸E差、和三楨差。隨著幀數(shù)的增加是防止檢測(cè)結(jié)果的重影。 2. 算法思路 步驟:
opencv中的absdiff可以用來(lái)求兩幅灰度圖像的差值圖像. 3. 代碼 # encoding=utf-8import datetimeimport imutilsimport timeimport cv2min_area = 500camera = cv2.VideoCapture(0)# 等待攝像頭準(zhǔn)備好time.sleep(0.25)# 初始化視頻流的第一幀firstFrame = None# 遍歷視頻的每一幀while True: # 獲取幀并初始化occupied/unoccupied文本 (grabbed, frame) = camera.read() text = 'Unoccupied' # 調(diào)整該幀的大小,轉(zhuǎn)換為灰階圖像并且對(duì)其進(jìn)行高斯模糊 frame = imutils.resize(frame, width=500) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (21, 21), 0) # 初始化第1幀 if firstFrame is None: firstFrame = gray continue # 差分 frameDelta = cv2.absdiff(firstFrame, gray) thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1] # 形態(tài)學(xué)操作 膨脹 thresh = cv2.dilate(thresh, None, iterations=2) thresh, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 遍歷輪廓 for c in contours: # if the contour is too small, ignore it print('area = %f ' % cv2.contourArea(c)) if cv2.contourArea(c) < min_area: continue # compute the bounding box for the contour, draw it on the frame, # and update the text # 計(jì)算輪廓的邊界框,在當(dāng)前幀中畫(huà)出該框 (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) text = 'Occupied' # draw the text and timestamp on the frame # 幀上寫(xiě)文字以及時(shí)間戳 cv2.putText(frame, 'Room Status: {}'.format(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('Security Feed', frame) cv2.imshow('Thresh', thresh) cv2.imshow('Frame Delta', frameDelta) key = cv2.waitKey(1) # q鍵跳出循環(huán) if key == ord('q'): break# 清理資源camera.release()cv2.destroyAllWindows() 運(yùn)行效果: |
|
來(lái)自: xpxys99 > 《計(jì)算機(jī)》