python opencv 幀差法目標檢測

2021-10-10 18:38:38 字數 2257 閱讀 7382

@author: qq群686070107

"""import cv2

import numpy as np

camera = cv2.videocapture(0)

# 引數0表示第乙個攝像頭

if(camera.isopened())

:print

('open'

)else

:print

('攝像頭未開啟'

)size =

(int

(camera.get(cv2.cap_prop_frame_width)),

int(camera.get(cv2.cap_prop_frame_height)))

print

('size:'

+repr

(size))

es = cv2.getstructuringelement(cv2.morph_ellipse,(9

,4))

kernel = np.ones((5

,5), np.uint8)

background =

none

while

true

: grabbed, frame_lwpcv = camera.read(

)# 對幀進行預處理,先轉灰度圖,再進行高斯濾波。

gray_lwpcv = cv2.cvtcolor(frame_lwpcv, cv2.color_bgr2gray)

gray_lwpcv = cv2.gaussianblur(gray_lwpcv,(21

,21),

0)# 將第一幀設定為整個輸入的背景

if background is

none

: background = gray_lwpcv

continue

# 對於每個從背景之後讀取的幀都會計算其與北京之間的差異,並得到乙個差分圖(different map)。

# 還需要應用閾值來得到一幅黑白影象,並通過下面**來膨脹(dilate)影象,從而對孔(hole)和缺陷(imperfection)進行歸一化處理

diff = cv2.absdiff(background, gray_lwpcv)

cv2.imshow(

'diff'

, diff)

diff = cv2.threshold(diff,

148,

255, cv2.thresh_binary)[1

]# 二值化閾值處理

diff = cv2.dilate(diff, es, iterations=2)

# 形態學膨脹

# 顯示矩形框

contours, hierarchy = cv2.findcontours(diff.copy(

)# 該函式計算一幅影象中目標的輪廓

for c in contours:

if cv2.contourarea(c)

<

1500

:# 對於矩形區域,只顯示大於給定閾值的輪廓,所以一些微小的變化不會顯示。對於光照不變和雜訊低的攝像頭可不設定輪廓最小尺寸的閾值

continue

(x, y, w, h)

= cv2.boundingrect(c)

# 該函式計算矩形的邊界框

cv2.rectangle(frame_lwpcv,

(x, y)

,(x+w, y+h),(

0,255,0)

,2)

cv2.imshow(

'contours'

, frame_lwpcv)

cv2.imshow(

'dis'

, diff)

key = cv2.waitkey(1)

&0xff

# 按'q'健退出迴圈

if key ==27:

break

# when everything done, release the capture

camera.release(

) cv2.destroyallwindows(

)

OpenCV實現幀差法

幀差法的優勢是運算量小,實時性好,可以獲得不錯的輪廓。缺點是不夠精細,閾值過高容易漏檢,過低則無法做到noise tolerance.另外如果發生光照突變等情況,幀差法會把整副影象當成運動區域。以下是實現的 include highgui.h include cv.h void main if fr...

Open CV 三幀差法

首先 去連續三幅圖定義為 其中image1 image2 做幀的差值運算 image2 image3 做幀的差值運算 並將他們差值做平滑處理和閾值處理 轉化成二值影象 然後將其進行位與運算得出結果result include highgui.h include cv.h include cxcore...

OpenCV運動目標檢測背景差法和幀差法的理解

上圖使用absdiff影象減法函式,如下 二值化腐蝕膨脹學習,幀差法和背景差法對比測試 include includeusing namespace cv using namespace std int main int argc,char ar 幀差法也是使用absdiff影象減法函式,只不過是相...