22.【實戰】車輛統計

專注的阿熊發表於2022-07-20

from asyncio import CancelledError

import cv2

from cv2 import erode

from cv2 import dilate

import numpy as np

# 濾除的最小矩形的範圍

min_w = 90

min_h = 90

# 定義檢測線的高度,與影片大小有關,影片左上角為( 0 0

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

cap = cv2.VideoCapture('E:\\video.mp4') # 載入影片

bgsubmog = cv2.createBackgroundSubtractorMOG2()

# 形態學 kernel

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))

while True:

     ret, frame = cap.read()

     if (ret == True) :

         # 灰度化處理

         cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

         # print(frame.shape)   # 獲取影片大小的資訊

         # exit()   # 該命令之後的所有程式都不執行

         # 去噪(高斯)

         blur = cv2.GaussianBlur(frame, (7,7),5)

         # 去背景

         mask = bgsubmog.apply(blur)

         # 腐蝕

         erode = cv2.erode(mask, kernel)

         # 膨脹

         dilate = cv2.dilate(erode, kernel, iterations= 2)

         # 形態學閉運算,去除影像裡面的噪點

         close = cv2.morphologyEx(dilate, 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)    #跟單網gendan5.com  將中心點資料儲存到 cars 這個陣列中

             for (x,y) in cars :   # 遍歷陣列,如果車的中心點落在檢測線的有效區域內,則計數 +1 ,然後去除該陣列

                 if ((y > line_high - offset) and (y < line_high + offset)):

                     carno += 1

                     cars.remove((x,y))  

                     print(carno)

         # 顯示統計資訊

         cv2.putText(frame, "Cars Count:" + str(carno),(500,60), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 0), 5)   

         cv2.imshow('video', frame)

         # cv2.imshow('close', close)   

     key = cv2.waitKey(1)

     if(key == 27) : # esc

         break

cap.release()

cv2.destroyAllWindows()


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2906797/,如需轉載,請註明出處,否則將追究法律責任。

相關文章