车道,又称行车线、车行道,是用在供车辆行经的道路,在一般公路和高速公路都有设置,高速公路对车道使用带有法律性质的规则,例如行车道和超车道。
import os
import re
import cv2
import numpy as np
from tqdm import tqdm_notebook
import matplotlib.pyplot as plt
# 获取帧的文件名
col_frames = os.listdir('frames/')
col_frames.sort(key=lambda f: int(re.sub('\D', '', f)))
# 加载帧
col_images=[]
for i in tqdm_notebook(col_frames):
img = cv2.imread('frames/'+i)
col_images.append(img)
让我们绘制一个帧:
# 指定一个索引
idx = 457
# plot frame
plt.figure(figsize=(10,10))
plt.imshow(col_images[idx][:,:,0], cmap= "gray")
plt.show()
# 创建0矩阵
stencil = np.zeros_like(col_images[idx][:,:,0])
# 指定多边形的坐标
polygon = np.array([[50,270], [220,160], [360,160], [480,270]])
# 用1填充多边形
cv2.fillConvexPoly(stencil, polygon, 1)
# 画出多边形
plt.figure(figsize=(10,10))
plt.imshow(stencil, cmap= "gray")
plt.show()
# 应用该多边形作为掩码
img = cv2.bitwise_and(col_images[idx][:,:,0], col_images[idx][:,:,0], mask=stencil)
# plot masked frame
plt.figure(figsize=(10,10))
plt.imshow(img, cmap= "gray")
plt.show()
# 应用图像阈值化
ret, thresh = cv2.threshold(img, 130, 145, cv2.THRESH_BINARY)
# 画出图像
plt.figure(figsize=(10,10))
plt.imshow(thresh, cmap= "gray")
plt.show()
lines = cv2.HoughLinesP(thresh, 1, np.pi/180, 30, maxLineGap=200)
# 创建原始帧的副本
dmy = col_images[idx][:,:,0].copy()
# 霍夫线
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(dmy, (x1, y1), (x2, y2), (255, 0, 0), 3)
# 画出帧
plt.figure(figsize=(10,10))
plt.imshow(dmy, cmap= "gray")
plt.show()
cnt = 0
for img in tqdm_notebook(col_images):
# 应用帧掩码
masked = cv2.bitwise_and(img[:,:,0], img[:,:,0], mask=stencil)
# 应用图像阈值化
ret, thresh = cv2.threshold(masked, 130, 145, cv2.THRESH_BINARY)
# 应用霍夫线变换
lines = cv2.HoughLinesP(thresh, 1, np.pi/180, 30, maxLineGap=200)
dmy = img.copy()
#画出检测到的线
try:
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(dmy, (x1, y1), (x2, y2), (255, 0, 0), 3)
cv2.imwrite('detected/'+str(cnt)+'.png',dmy)
except TypeError:
cv2.imwrite('detected/'+str(cnt)+'.png',img)
cnt+= 1
# 输入帧的路径
pathIn= 'detected/'
#输出视频路径
pathOut = 'roads_v2.mp4'
# 视频每秒的帧数
fps = 30.0
from os.path import isfile, join
# 获取帧的文件名
files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]
files.sort(key=lambda f: int(re.sub('\D', '', f)))
接下来,我们将把检测到的车道上的所有帧放入一个列表中:
frame_list = []
for i in tqdm_notebook(range(len(files))):
filename=pathIn + files[i]
#读取每一个文件
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width,height)
#将帧插入图像数组
frame_list.append(img)
最后,我们现在可以使用下面的代码将帧合并为视频:
# 写入视频
out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'DIVX'), fps, size)
for i in range(len(frame_array)):
out.write(frame_array[i])
out.release()
这就完成了Python中的车道检测系统。
感谢大家的走心留言,每一条小编都认真阅读了,会继续努力哒。
这次没被抽中的朋友不要气馁~ 我们会 坚持不定期推出留言送书活动,多多留言会增加中奖概率的。恭喜下面留言的两位读者,分别获赠书籍《 Python数据分析与可视化从入门到精通》一本。请联系小编: mthler。 ☆ END ☆ 如果看到这里,说明你喜欢这篇文章,请 转发、点赞 。微信搜索「uncle_pn」,欢迎添加小编微信「 mthler」,每日朋友圈更新一篇 高质量博文 (无广告)。 ↓扫描二维码添加小编↓