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))  # 定义结构元素
    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.dilate(draw1, kernel, iterations=1)
        if nn<20: #判断20帧内有入侵动作
            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>15000 and iouArea<40000:
            return True#'1'
        else:
            return False #'0'
    else:
        return False #'0'

if __name__ == '__main__':
    pfile = "videos/20230130-100958_e5910f7d-90dd-4f6b-9468-689ba45fe656.mp4"
    mask_path = 'models/lianhua_1.jpg'
    #frame_path = 'frame'
    #result_path = 'result'
    get_object_location(pfile, mask_path)

