
導語?
SO 由于對考試,車輛有了執著,所以學習以及今天教大家的也是關于基于opencv的車輛檢測系統!!!

正文
想想看,如果你能在紅綠燈攝像頭中集成車輛檢測系統,你可以輕松地同時跟蹤許多有用的東西:
-
白天交通路口有多少輛車?
-
什么時候交通堵塞?
-
什么樣的車輛(重型車輛、汽車等)正在通過交叉路口?
-
有沒有辦法優化交通,并通過不同的街道進行分配?
還有很多例子就不一一列舉,應用程式是無止境的~

首先環境安裝:
我們先匯入所需的庫和模塊—— opencv安裝:pip install opencv-python
import os
import re
import cv2 # opencv library
import numpy as np
from os.path import isfile, join
import matplotlib.pyplot as plt
將框架保存在作業目錄中的檔案夾以及匯入幀并保存:
# get file names of the frames
col_frames = os.listdir('frames/')
# sort file names
col_frames.sort(key=lambda f: int(re.sub('\D', '', f)))
# empty list to store the frames
col_images=[]
for i in col_frames:
# read the frames
img = cv2.imread('frames/'+i)
# append the frames to the list
col_images.append(img)
讓我們顯示兩個連續的幀:
# plot 13th frame
i = 13
for frame in [i, i+1]:
plt.imshow(cv2.cvtColor(col_images[frame], cv2.COLOR_BGR2RGB))
plt.title("frame: "+str(frame))
plt.show()

?
獲取兩個連續幀的像素值的差值將有助于我們觀察移動目標,那么,讓我們在上面兩個幀上使用該技術:
# convert the frames to grayscale
grayA = cv2.cvtColor(col_images[i], cv2.COLOR_BGR2GRAY)
grayB = cv2.cvtColor(col_images[i+1], cv2.COLOR_BGR2GRAY)
# plot the image after frame differencing
plt.imshow(cv2.absdiff(grayB, grayA), cmap = 'gray')
plt.show()

?
現在我們可以清楚地看到第13幀和第14幀中的移動目標,其他沒有移動的東西都被減去了,
影像預處理——為所有幀中的所有移動車輛添加了輪廓:
# specify video name
pathOut = 'vehicle_detection_v3.mp4'
# specify frames per second
fps = 14.0
接下來閱讀串列中的最后一幀:
frame_array = []
files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]
files.sort(key=lambda f: int(re.sub('\D', '', f)))
for i in range(len(files)):
filename=pathIn + files[i]
#read frames
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width,height)
#inserting the frames into an image array
frame_array.append(img)
最后使用以下代碼制作目標檢測視頻:
out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'DIVX'), fps, size)
for i in range(len(frame_array)):
# writing to a image array
out.write(frame_array[i])
out.release()
好啦!你學會了嘛?
總結
祈禱下次科二考試一定過!一定過!一定過!!

如果看到這里,說明你喜歡這篇文章,記得三連哦~愛你,
小編最后還會給大家分享一些python大禮包【加君羊:605018913】幫助大家更好的學習python!

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/382787.html
標籤:AI
上一篇:嘿嘿,幾行代碼秒出美女素描圖
