admin 发表于 2022-8-5 13:04:01

opencv车辆检测系统

import cv2
import numpy as np

cap = cv2.VideoCapture('video.mp4')
bg = cv2.bgsegm.createBackgroundSubtractorMOG()
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
min_w = 90
min_h = 90
#检测线的高度
line_high = 550
#线的偏移量
offset = 7
#统计车的数量
carno = 0
#存放有效车辆数组
cars = []
#定义中心点
def center (x, y, w, h):
    x1 = int(w/2)
    y1 = int(h/2)
    cx = x + x1
    cy = y + y1
    return cx, cy

#循环去读取视频中的每一帧 视频是由一幅幅图画组成的
while True:
    #ret判断读取视频的帧是否成功了,成功了还返回另一个值frame
    ret, frame = cap.read()
    if (ret == True):
      #灰度化
      cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      #高斯去噪
      blur = cv2.GaussianBlur(frame, (3, 3), 5)
      #去背景
      mask = bg.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, (10, line_high), (1200, line_high), (255,255,0), 3)

      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, 0, 255), 2)
            cpoint = center(x, y, w, h)
            cars.append(cpoint)

            for (x, y) in cars:
                # 要有一条线 有范围(6个像素) 从数组中间去
                if ((y < line_high + offset) and (y > line_high - offset)):
                  carno +=1
                  cars.remove((x, y))
                  print(carno)
      cv2.putText(frame, "Cars Counts:" + str(carno), (500,60),
                  cv2.FONT_HERSHEY_SIMPLEX, 2, (255,0,0), 5)
      cv2.imshow("video", frame)

    else:
      break


    key = cv2.waitKey(1)
    if(key == 27):
      break


cap.release()
cv2.destroyAllWindows()


页: [1]
查看完整版本: opencv车辆检测系统