听说拍人家违章月入十万?那我用python写个自动检测车辆是否违章不是发财了?
导语
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!
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
二维码
)">