''' 处理摄像头数据,并在第一幁画线 1、定义鼠标事件(返回初始点,和结束点) 2、利用初始点和结束点画线 ''' import cv2 from vibe import ViBe import numpy as np from cross_line import verify_rec # from ssd import vs drawing = False # true if mouse is pressed mode = False # if True, draw rectangle. Press 'm' to toggle to curve ix,iy = -1,-1 beginPoint = (-1,-1) endPoint = (-1,-1) # mouse callback function def draw_circle(event,x,y,flags,param): global ix,iy,drawing,mode,beginPoint,endPoint if event == cv2.EVENT_LBUTTONDOWN: drawing = True ix,iy = x,y beginPoint = (x,y) if drawing: print('起始点',(ix,iy)) elif event == cv2.EVENT_MOUSEMOVE: if drawing == True: # print('图片',img) endPoint = (x,y) elif event == cv2.EVENT_LBUTTONUP: drawing = False mode = True print('终点',(x,y)) endPoint = (x,y) cap = cv2.VideoCapture('video/1.avi') ret, frame = cap.read() img = frame frame = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) vibe = ViBe() vibe.ProcessFirstFrame(frame) cv2.namedWindow('image') cv2.setMouseCallback('image', draw_circle) while(mode==False): cv2.line(img, beginPoint, endPoint, (0, 0, 255), 3) cv2.imshow('image',img) if cv2.waitKey(50) & 0xFF == ord('q'): break print('=========') while(cap.isOpened()): ret, img = cap.read() cv2.line(img,beginPoint,endPoint,(0,0,255),3) if ret: # 将输入转为灰度图 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 输出二值图 # (segMat, samples) = update(gray, samples) vibe.Update(gray) segMat = vibe.getFGMask() # 转为uint8类型 segMat = segMat.astype(np.uint8) # 形态学处理模板初始化 kernel1 = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)) # 开运算 opening = cv2.morphologyEx(segMat, cv2.MORPH_OPEN, kernel1) # 形态学处理模板初始化 kernel2 = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)) # 闭运算 closed = cv2.morphologyEx(segMat, cv2.MORPH_CLOSE, kernel2) # 寻找轮廓 # contours, hierarchy = cv2.findContours(closed, mode=cv2.RETR_TREE, method=cv2.CHAIN_APPROX_SIMPLE) _, contours, hierarchy = cv2.findContours(opening, mode=cv2.RETR_TREE, method=cv2.CHAIN_APPROX_SIMPLE) # for j in range(40, 10000, 20): # print('当前框的大小:', j) print('目标数量:',len(contours)) for i in range(0, len(contours)): x, y, w, h = cv2.boundingRect(contours[i]) object_min = (x,y) object_max = (x + w, y + h) print(w*h) if w * h > 50 and w * h < 10000: if verify_rec(beginPoint,endPoint,object_min,object_max): cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2) else: cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) # cv2.imshow("frame", frame) cv2.imshow('image',img) if cv2.waitKey(20) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
利用vibe实现越界检测
最新推荐文章于 2024-02-07 12:13:35 发布