Files
ieemoo-ai-filtervideo/checkobject.py
2023-03-02 16:22:49 +08:00

76 lines
2.4 KiB
Python

import cv2 as cv
#from segmentation import get_object_mask
import os, time
def get_object_location(pfile, mask_path = 'lianhua_1.jpg'):
kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (3, 3)) # 定义膨胀结构元素
kernel1 = cv.getStructuringElement(cv.MORPH_ELLIPSE, (2, 2)) # 定义腐蚀结构元素
fgbg = cv.createBackgroundSubtractorMOG2(detectShadows=False)
nu, nn = 0, 1
flag = False
T1 = time.time()
# 设置文件
cap = cv.VideoCapture(pfile)
while True:
# 读取一帧
ret, frame = cap.read()
nn += 1
if (not ret):
break
if flag:
flag = False
print('flag change>>{}>>{}'.format(pfile, nn))
return '1'
frame = cv.resize(frame, (512, 640), interpolation=cv.INTER_CUBIC)
frame = cv.medianBlur(frame, ksize=3)
frame_motion = frame.copy()
# 计算前景掩码
fgmask = fgbg.apply(frame_motion)
draw1 = cv.threshold(fgmask, 25, 255, cv.THRESH_BINARY)[1] # 二值化
draw1 = cv.erode(draw1, kernel1, iterations=2)
draw1 = cv.dilate(draw1, kernel, iterations=1)
cv.imwrite('data/tmp/'+str(nn)+'.jpg', draw1)
if nn<80: #判断80帧内有入侵动作
flag = check_tings(mask_path, draw1)
T2 = time.time()
print('single video >>> {}-->{}-->{}'.format(pfile, nn, (T2 - T1)))
return '0'
def check_tings(mask_path, img):
dics = {}
mask_img = cv.imread(mask_path)
img = cv.bitwise_and(mask_img[:,:,0], img)
contours_m, hierarchy_m = cv.findContours(img.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
for contour in contours_m:
dics[len(contour)] = contour
if len(dics.keys()) > 0:
cc = sorted(dics.keys())
iouArea = cv.contourArea(dics[cc[-1]])
#print('iouara>>>>>>> {}'.format(iouArea))
if iouArea>3000 and iouArea<50000:
return True
else:
return False
else:
return False
if __name__ == '__main__':
path = "data/test"
mask_path = 'lianhua_1.jpg'
#frame_path = 'frame'
#result_path = 'result'
nn = 0
names = []
for name in os.listdir(path):
pfile = os.sep.join([path, name])
flag = get_object_location(pfile, mask_path)
if flag == '0':
nn += 1
names.append(name)
#print('<><><><><<><{}'.format(nn))
#print('<><><><><<><{}'.format(names))