本文實(shí)例為大家分享了python+opencv實(shí)現(xiàn)移動(dòng)偵測(cè)的具體代碼,供大家參考,具體內(nèi)容如下

1.幀差法原理
移動(dòng)偵測(cè)即是根據(jù)視頻每幀或者幾幀之間像素的差異,對(duì)差異值設(shè)置閾值,篩選大于閾值的像素點(diǎn),做掩模圖即可選出視頻中存在變化的楨。幀差法較為簡(jiǎn)單的視頻中物體移動(dòng)偵測(cè),幀差法分為:單幀差、兩楨差、和三楨差。隨著幀數(shù)的增加是防止檢測(cè)結(jié)果的重影。
2.算法思路
文章以截取視頻為例進(jìn)行單幀差法移動(dòng)偵測(cè)
3.python實(shí)現(xiàn)代碼
def threh(video,save_video,thres1,area_threh):
cam = cv2.VideoCapture(video)#打開一個(gè)視頻
input_fps = cam.get(cv2.CAP_PROP_FPS)
ret_val, input_image = cam.read()
index=[]
images=[]
images.append(input_image)
video_length = int(cam.get(cv2.CAP_PROP_FRAME_COUNT))
input_image=cv2.resize(input_image,(512,512))
ending_frame = video_length
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(save_video,fourcc, input_fps, (512, 512))
gray_lwpCV = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
gray_lwpCV = cv2.GaussianBlur(gray_lwpCV, (21, 21), 0)
background=gray_lwpCV
# es = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 4))
i = 0 # default is 0
outt=[]
while(cam.isOpened()) and ret_val == True and i <2999:
## if i % 2==1:
ret_val, input_image = cam.read()
input_image=cv2.resize(input_image,(512,512))
gray_lwpCV = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
gray_lwpCV = cv2.GaussianBlur(gray_lwpCV, (21, 21), 0)
diff = cv2.absdiff(background, gray_lwpCV)
outt.append(diff)
#跟著圖像變換背景
tem_diff=diff.flatten()
tem_ds=pd.Series(tem_diff)
tem_per=1-len(tem_ds[tem_ds==0])/len(tem_ds)
if (tem_per <0.2 )| (tem_per>0.75):
background=gray_lwpCV
else:
diff = cv2.threshold(diff, thres1, 255, cv2.THRESH_BINARY)[1]
ret,thresh = cv2.threshold(diff.copy(),150,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
# contours, hierarchy = cv2.findContours(diff.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
if (cv2.contourArea(c) < area_threh) | (cv2.contourArea(c) >int(512*512*0.3) ) : # 對(duì)于矩形區(qū)域,只顯示大于給定閾值的輪廓(去除微小的變化等噪點(diǎn))
continue
(x, y, w, h) = cv2.boundingRect(c) # 該函數(shù)計(jì)算矩形的邊界框
cv2.rectangle(input_image, (x, y), (x+w, y+h), (0, 255, 0), 2)
index.append(i)
# cv2.imshow('contours', input_image)
# cv2.imshow('dis', diff)
out.write(input_image)
images.append(input_image)
i = i+1
out.release()
cam.release()
return outt,index,images```
##調(diào)取函數(shù)
outt=threh('new_video.mp4','test6.mp4',25,3000)
本文名稱:python+opencv實(shí)現(xiàn)移動(dòng)偵測(cè)(幀差法)-創(chuàng)新互聯(lián)
文章源于:http://chinadenli.net/article18/dpigdp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站設(shè)計(jì)、靜態(tài)網(wǎng)站、網(wǎng)站收錄、搜索引擎優(yōu)化、電子商務(wù)、網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)