#加载视频 import cv2 import numpy as np cap = cv2.VideoCapture('car.mp4') #去除背景 mog= cv2.bgsegm.createBackgroundSubtractorMOG() kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(7,7)) min_w=90 min_h=90 line_hig=400 #偏移量 offset=2 cars=[] carno=0 #计算外矩形的中心点 def center(x,y,w,h): x1=int(w/2) y1=int(h/2) cx=int(x)+x1 cy=int(y)+y1 return cx,cy #循环读取视频帧 while True: ret,frame = cap.read() if ret == True: # 把原始帧进行灰度化 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #采用高斯去噪 blur = cv2.GaussianBlur(gray,(7,7),8) fgmask = mog.apply(blur) #腐蚀 erode = cv2.erode(fgmask,kernel) #膨胀,把图像还原回来 dialte=cv2.dilate(erode,kernel,iterations=2) #消除内部的小块 # 执行开运算 opening = cv2.morphologyEx(dialte, cv2.MORPH_OPEN, kernel) #闭运算 close=cv2.morphologyEx(opening,cv2.MORPH_CLOSE,kernel) #查找轮廓 result,contours,h=cv2.findContours(close,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # 如何画线,画在什么位置 cv2.line(frame,(10,line_hig),(1600,line_hig),(255,255,0),3) #画出所有检测的轮廓 for contour in contours: #最大外接矩形 (x,y,w,h)=cv2.boundingRect(contour) #通过外接矩形的宽高大小来过滤掉小的矩形 is_valid = (w>=min_w)&(h>=min_h) if not is_valid: continue #要求坐标点数都是整数 cv2.rectangle(frame,(int(x),int(y)),(int(x+w),int(y+h)),(0,0,255),2) #把车抽象为一点,即外接矩形的中心点 #要通过外接矩形计算矩形的中心点 cpoint=center(x,y,w,h) cars.append(cpoint) cv2.circle(frame,(cpoint),5,(0,0,255),-1) #判断汽车是否过线 # 如何画线,画在什么位置 #如何去计数 for(x,y) in cars: if y>(line_hig-offset) and y<(line_hig+offset): #落入有郊期间 carno+=1 cars.remove((x,y)) print(carno) #cv2.imshow('video',erode) #cv2.imshow('opening', opening) cv2.putText(frame,'Vehicle Count:'+str(carno),(500,60),cv2.FONT_HERSHEY_SIMPLEX,2,(0,0,255),5) cv2.imshow('frame', frame) key= cv2.waitKey(2) #用户按ESC退出 if key ==27: break #释放资源 cap.release() cv2.destroyAllWindows()