Python实现动态目标检测-帧差法、时间平均法、单高斯法

动态目标检测

1.帧差法

# 帧差法
import cv2
cap = cv2.VideoCapture('raw.avi')
ret, frame = cap.read()
h, w = frame.shape[:2]
while True:
    ret, frame = cap.read()
    ret, frame_next = cap.read()
    if ret == False:
        break
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    frame_next = cv2.cvtColor(frame_next, cv2.COLOR_BGR2GRAY)
    frame_delta = cv2.absdiff(frame_next, frame)
    ret, thresh = cv2.threshold(frame_delta, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    cv2.imshow('thresh', thresh)
    if cv2.waitKey(30) == 27:
        break
cap.release()
cv2.destroyAllWindows()

2.时间平均法

# 时间平均法
import cv2
import glob
import numpy as np

namelist = glob.glob('./frames/*.bmp')
img = cv2.imread(namelist[0], 0)
h, w = img.shape[:2]
N = 100      # select the first 40 frame for modeling
mu = np.zeros((h,w), np.uint8)
for i in range(N):
    frame = cv2.imread(namelist[i], 0)
    gaussian = cv2.GaussianBlur(frame, (5,5), 0)
    mu = (mu * i + gaussian) / (i+1)

mu = np.array(mu, dtype=np.uint8)

cnt = 0
for i in range(N, len(namelist)):
    frame = cv2.imread(namelist[i], 0)
    gaussian = cv2.GaussianBlur(frame, (5,5), 0)
    mu = mu / i * (i - 1) + gaussian/ i   # update mean image
    mu = np.array(mu, dtype=np.uint8)
    frame = np.array(frame, dtype=np.uint8)
    result = cv2.absdiff(frame, mu)
    ret, thresh = cv2.threshold(result, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    cv2.imshow('thresh', thresh)
    if cv2.waitKey(30) == 27:
        break

3.单高斯法

#单高斯法
import cv2
import glob
import numpy as np

namelist = glob.glob('./frames/*.bmp')
img = cv2.imread(namelist[0], 0)
mu = cv2.GaussianBlur(img, (5,5), 0)
h, w = img.shape[:2]
cov = np.zeros((h, w))
pro = np.zeros((h, w))
sav_mu = mu
a = 0.01
N = 40
for i in range(1,N):
    frame  = cv2.imread(namelist[i], 0)
    blur = cv2.GaussianBlur(frame, (5,5), 0)
    mu = (blur+(i-1)*sav_mu)/i
    cov = ((blur- mu)**2 + (i - 1) * cov)/ i + (mu - sav_mu)**2
    sav_mu = mu
cov = cov + 0.1
cnt = 0
for num in range(N+1, len(namelist)):
    cnt += 1
    frame = cv2.imread(namelist[num], 0)
    blurImg = cv2.GaussianBlur(frame, (5,5), 0)
    T = 1e-8
    pro = (2 * np.pi)**(-0.5) * np.exp(-0.5 * (blurImg - mu)**2 / cov) / np.sqrt(cov)
    ret, pro = cv2.threshold(pro, T, 255, cv2.THRESH_BINARY)
    mu = mu +a*(1-pro)*(blurImg - mu)
    cov = cov + a*(1-pro)*((blurImg - mu)**2-cov)
    cv2.imshow('cov', cov)
    if cv2.waitKey(10) == 27:
        break

 

 

 

 

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试