CV Python - 3 动态目标检测

动态目标检测

1.帧差法

dir = r"H:\动态目标分割\\"
cap = cv2.VideoCapture(dir + 'raw.avi')
ret, frame = cap.read()
print(frame.shape)
h, w = frame.shape[:2]
# 帧差法
cnt = 0
while(1):
    cnt += 1
    frame = cap.read()[1]
    frame_1 = cap.read()[1]
    frameDelta = cv2.absdiff(frame_1, frame)
    binary = cv2.threshold(frameDelta, 40, 255, cv2.THRESH_BINARY)[1]
    cv2.imshow("capture", binary)
    if(cnt == 225):cv2.waitKey(0)
    if cv2.waitKey(20) & 0xFF == ord('q'): break
cap.release()
cv2.destroyAllWindows()

2.时间平均法

# 时间平均法
def eachFile(filepath):
    list = []
    pathDir = os.listdir(filepath)
    for allDir in pathDir:
        child = os.path.join(filepath, allDir)
        list.append(child)
    return list
pic_list = eachFile(dir + 'RawImages\\')
pic = cv2.cvtColor(plt.imread(pic_list[0]), cv2.COLOR_BGR2GRAY)
h, w = pic.shape[:2]
N = 40
gaussian = filters.gaussian(pic, sigma=1)
mu = gaussian
for i in range(N):
    pic  = plt.imread(pic_list[i])
    pic = cv2.cvtColor(pic, cv2.COLOR_BGR2GRAY)
    gaussian = filters.gaussian(pic, sigma=1)
    mu += gaussian
mu = mu / N

cnt = 0
for num in range(N+1, 500):
    pic = cv2.cvtColor(plt.imread(pic_list[num]), cv2.COLOR_BGR2GRAY)
    # pic = filters.gaussian(pic, sigma=1)
    t = 20
    mu = (mu * (num - 1) + pic) / num
    mu = np.array(mu, dtype = np.float32)
    pic = np.array(pic, dtype = np.float32)
    pro = cv2.absdiff(pic, mu)
    binary = cv2.threshold(pro, 40, 255, cv2.THRESH_BINARY)[1]
    cv2.imshow('t', binary)
    if cv2.waitKey(20) & 0xFF == ord('q'): break

3.单高斯法

#单高斯法
mu = filters.gaussian(pic, sigma=3)
cov = np.zeros((h, w))
pro = np.zeros((h, w))
sav_mu = mu
a = 0.01
for i in range(1,N):
    pic  = plt.imread(pic_list[i])
    pic = cv2.cvtColor(pic, cv2.COLOR_BGR2GRAY)
    tmp = filters.gaussian(pic, sigma=3)
    mu = (tmp+(i-1)*sav_mu)/i
    cov = ((tmp - mu)**2 + (i - 1) * cov)/ (i) + (mu - sav_mu)**2;
    sav_mu = mu
cov = cov + 0.001
cnt = 0
for num in range(N+1, 501):
    cnt += 1
    pic = plt.imread(pic_list[num])
    pic = cv2.cvtColor(pic, cv2.COLOR_BGR2GRAY)
    imagedata = filters.gaussian(pic, sigma=1)
    T = 1e-8
    pro = (2 * np.pi)**(-1 / 2) * np.exp(-0.5 * (imagedata - mu)**2/ cov)/ np.sqrt(cov)
    pro = cv2.threshold(pro, T, 255, cv2.THRESH_BINARY)[1]
    mu = mu +a*(1-pro)*(imagedata-mu)
    cov = cov + a*(1-pro)*((imagedata-mu)**2-cov)
    # pic = cv2.cvtColor(pro, cv2.COLOR_BGR2GRAY)
    cv2.imshow('t', pro)
    if (cnt == 400): cv2.waitKey(0)
    if cv2.waitKey(20) & 0xFF == ord('q'): break

#涉及的库

import cv2
import numpy as np
import os
import matplotlib.pyplot as plt
from skimage import filters


阅读更多
想对作者说点什么? 我来说一句

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

关闭
关闭
关闭