import cv2
import numpy
def center(x, y, w, h):
x1 = int(w/2)
y1 = int(h/2)
cx = x + x1
cy = y + y1
return cx, cy
min_w = 90
min_h = 90
#检测线的高宽度
line_height = 550
line_wide1 = 10
line_wide2 = 1200
line_mid = (line_wide1+line_wide2)/2
#线的偏移量
offset = 6
carnum1 = 0
carnum2 = 0
cars = []
#引入视频文件
cap = cv2.VideoCapture('/Users/yangminghui/Downloads/yolov8_GUI-main/yolov8test.mp4')
winname = 'video'
bgsubmog = cv2.bgsegm.createBackgroundSubtractorMOG()
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
while True:
ret, frame = cap.read()
if(ret == True):
#灰度化
cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
#高斯去噪
blur = cv2.GaussianBlur(frame, (3, 3), 5)
#去背景
mask = bgsubmog.apply(blur)
#腐蚀 去掉图中小方块
erode = cv2.erode(mask,kernel)
#膨胀
dilate = cv2.dilate(erode,kernel, iterations=3)
#闭操作,去除物体内部的小块
close = cv2.morphologyEx(dilate, cv2.MORPH_CLOSE, kernel)
close = cv2.morphologyEx(close, cv2.MORPH_CLOSE, kernel)
#查找轮廓
cnts, h = cv2.findContours(close,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#绘制检测线
cv2.line(frame, (line_wide1, line_height),(line_wide2,line_height),(255, 255, 0))
#cv2.line(frame, (300, 315), (889,250), (255, 0, 0), 5)
for(i,c) in enumerate(cnts):
(x, y, w, h) = cv2.boundingRect(c)
#对车辆宽高进行判断,验证是否是有效车辆
isValid = (w >= min_w) and(h >= min_h)
if(not isValid):
continue
#如果是有效车辆,则绘制边框
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cpoint = center(x, y, w, h)#计算汽车中心点
cars.append(cpoint)
cv2.circle(frame, (cpoint), 5, (0, 0, 255), -1)
for(x, y) in cars:# 遍历数组,如果车的中心点落在检测线的有效区域内,则计数+1,然后去除该数组
print(y,line_height-offset,line_height+offset)
if( (y > line_height - offset )and (y < line_height + offset))and(x<line_mid):
carnum1 += 1
cars.remove((x, y))
print(carnum1)
if( (y > line_height - offset )and (y < line_height + offset))and(x>line_mid):
carnum2 += 1
cars.remove((x, y))
print(carnum2)
text_lines = ["cars_in:"+str(carnum1),"cars_out:"+str(carnum2)]
text_start_pos=(500,60)
for i,text in enumerate(text_lines):
y_height = text_start_pos[1]+ i*30
cv2.putText(frame,text,(text_start_pos[0],y_height), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0),5)
cv2.imshow('close', close)
cv2.imshow(winname, frame)
key = cv2.waitKey(1)
if (key == 27):#esc键
break
cap.release()
cv2.destroyAllWindows()
网友评论