基于opencv的前景提取项目。
视频演示:
opecv差帧法提取前景
b站地址:b站观看
高斯混合模型代码:
import copy
import numpy as np
import cv2 as cv
fgbg=cv.createBackgroundSubtractorMOG2()
kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (3, 3))
def aa(frame):
frame_copy=copy.deepcopy(frame)
# kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (3, 3))
global kernel
fgmask = fgbg.apply(frame)
# 形态学处理
fgmask = cv.morphologyEx(fgmask, cv.MORPH_OPEN, kernel)
# 膨胀
kernel = np.ones((3, 3), np.uint8)
# erroding = cv.erode(fgmask, kernel)
dilation = cv.dilate(fgmask, kernel)
# cv.imshow('a12',dilation)
# cv.waitKey(100)
_, dilation = cv.threshold(dilation, 200, 255, cv.THRESH_BINARY)
contours, hierarchy = cv.findContours(dilation, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
for c in contours:
perimeter = cv.arcLength(c, True)
#print(perimeter)
if perimeter > 55:
x, y, w, h = cv.boundingRect(c)
if w>2*h:
pass
else:
cv.rectangle(frame_copy, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv.rectangle(frame_copy, (x, y - 16), (x + 70, y), (0, 0, 255), -1)
cv.putText(frame_copy, 'persion', (x, y - 5), cv.FONT_HERSHEY_COMPLEX, 0.5, (0, 255, 255), 1)
return frame_copy,dilation
if __name__ == '__main__':
pass
差帧法代码:
import cv2 as cv
import numpy as np
from gaoshi import aa
cap = cv.VideoCapture("./video/test2.avi")
a=0
zhen2=0
zhen3=0
zhen4=0
zhen5=0
zftu_hou=0
while True:
a+=1
ret, frame = cap.read()
frame=cv.resize(frame,(531,398))
# 高斯滤波
frame = cv.GaussianBlur(frame, (3,3), 0)
gray=cv.cvtColor(frame,cv.COLOR_BGR2GRAY)
zhen1 = zhen2
zhen2=zhen3
zhen3 = zhen4
zhen4=zhen5
zhen5=gray
#print('zhen1=',np.sum(zhen1),'zhen2=',np.sum(zhen2),'zhen3=',np.sum(zhen3))
if a>=5:
kernel = np.ones((3, 3), np.uint8)
diff=cv.absdiff(zhen1,zhen5)
#膨胀
diff = cv.dilate(diff, kernel)
#print(diff.shape)
_,diff=cv.threshold(diff,10,255,cv.THRESH_BINARY)
fras,dilation=aa(frame)
#形态学操作
# 膨胀
dilation = cv.dilate(dilation, kernel)
dilation = cv.erode(dilation, kernel)
contours, hierarchy = cv.findContours(dilation, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
for c in contours:
perimeter = cv.arcLength(c, True)
#print(perimeter)
if perimeter > 55:
x, y, w, h = cv.boundingRect(c)
if w>2*h:
pass
else:
cv.rectangle(fras, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv.rectangle(fras, (x, y - 16), (x + 70, y), (0, 0, 255), -1)
cv.putText(fras, 'persion', (x, y - 5), cv.FONT_HERSHEY_COMPLEX, 0.5, (0, 255, 255), 1)
jiao=np.where((dilation==255)|(diff==255),255,0)
jiao=jiao.astype('uint8')
cv.imshow("jiao", jiao)
cv.imshow("diff", diff)
cv.imshow("fras", fras)
cv.imshow("dilation", dilation)
# cv.imshow("gray", frame)
cv.waitKey(100)
项目目录:
运行main.py即可!
**项目下载地址(带界面):https://gitee.com/mqwdasddqw/project-download-address