智慧交通day03-车道线检测实现09:车道线检测代码汇总(Python3.8)
生活随笔
收集整理的這篇文章主要介紹了
智慧交通day03-车道线检测实现09:车道线检测代码汇总(Python3.8)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import cv2
import numpy as np
import matplotlib.pyplot as plt
#遍歷文件夾
import glob
from moviepy.editor import VideoFileClip"""參數設置"""
nx = 9
ny = 6
#獲取棋盤格數據
file_paths = glob.glob("./camera_cal/calibration*.jpg")# # 繪制對比圖
# def plot_contrast_image(origin_img, converted_img, origin_img_title="origin_img", converted_img_title="converted_img",
# converted_img_gray=False):
# fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 20))
# ax1.set_title = origin_img_title
# ax1.imshow(origin_img)
# ax2.set_title = converted_img_title
# if converted_img_gray == True:
# ax2.imshow(converted_img, cmap="gray")
# else:
# ax2.imshow(converted_img)
# plt.show()#相機矯正使用opencv封裝好的api
#目的:得到內參、外參、畸變系數
def cal_calibrate_params(file_paths):#存儲角點數據的坐標object_points = [] #角點在真實三維空間的位置image_points = [] #角點在圖像空間中的位置#生成角點在真實世界中的位置objp = np.zeros((nx*ny,3),np.float32)#以棋盤格作為坐標,每相鄰的黑白棋的相差1objp[:,:2] = np.mgrid[0:nx,0:ny].T.reshape(-1,2)#角點檢測for file_path in file_paths:img = cv2.imread(file_path)#將圖像灰度化gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#角點檢測rect,coners = cv2.findChessboardCorners(gray,(nx,ny),None)#若檢測到角點,則進行保存 即得到了真實坐標和圖像坐標if rect == True :object_points.append(objp)image_points.append(coners)# 相機較真ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(object_points, image_points, gray.shape[::-1], None, None)return ret, mtx, dist, rvecs, tvecs# 圖像去畸變:利用相機校正的內參,畸變系數
def img_undistort(img, mtx, dist):dis = cv2.undistort(img, mtx, dist, None, mtx)return dis#車道線提取
#顏色空間轉換--》邊緣檢測--》顏色閾值--》并且使用L通道進行白色的區域進行抑制
def pipeline(img,s_thresh = (170,255),sx_thresh=(40,200)):# 復制原圖像img = np.copy(img)# 顏色空間轉換hls = cv2.cvtColor(img,cv2.COLOR_RGB2HLS).astype(np.float)l_chanel = hls[:,:,1]s_chanel = hls[:,:,2]#sobel邊緣檢測sobelx = cv2.Sobel(l_chanel,cv2.CV_64F,1,0)#求絕對值abs_sobelx = np.absolute(sobelx)#將其轉換為8bit的整數scaled_sobel = np.uint8(255 * abs_sobelx / np.max(abs_sobelx))#對邊緣提取的結果進行二值化sxbinary = np.zeros_like(scaled_sobel)#邊緣位置賦值為1,非邊緣位置賦值為0sxbinary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1#對S通道進行閾值處理s_binary = np.zeros_like(s_chanel)s_binary[(s_chanel >= s_thresh[0]) & (s_chanel <= s_thresh[1])] = 1# 結合邊緣提取結果和顏色通道的結果,color_binary = np.zeros_like(sxbinary)color_binary[((sxbinary == 1) | (s_binary == 1)) & (l_chanel > 100)] = 1return color_binary#透視變換-->將檢測結果轉換為俯視圖。
#獲取透視變換的參數矩陣【二值圖的四個點】
def cal_perspective_params(img,points):# x與y方向上的偏移offset_x = 330offset_y = 0#轉換之后img的大小img_size = (img.shape[1],img.shape[0])src = np.float32(points)#設置俯視圖中的對應的四個點 左上角 右上角 左下角 右下角dst = np.float32([[offset_x, offset_y], [img_size[0] - offset_x, offset_y],[offset_x, img_size[1] - offset_y], [img_size[0] - offset_x, img_size[1] - offset_y]])## 原圖像轉換到俯視圖M = cv2.getPerspectiveTransform(src, dst)# 俯視圖到原圖像M_inverse = cv2.getPerspectiveTransform(dst, src)return M, M_inverse#根據透視變化矩陣完成透視變換
def img_perspect_transform(img,M):#獲取圖像大小img_size = (img.shape[1],img.shape[0])#完成圖像的透視變化return cv2.warpPerspective(img,M,img_size)# 精確定位車道線
#傳入已經經過邊緣檢測的圖像閾值結果的二值圖,再進行透明變換
def cal_line_param(binary_warped):#定位車道線的大致位置==計算直方圖histogram = np.sum(binary_warped[:,:],axis=0) #計算y軸# 將直方圖一分為二,分別進行左右車道線的定位midpoint = np.int(histogram.shape[0]/2)#分別統計左右車道的最大值midpoint = np.int(histogram.shape[0] / 2)leftx_base = np.argmax(histogram[:midpoint]) #左車道rightx_base = np.argmax(histogram[midpoint:]) + midpoint #右車道#設置滑動窗口#對每一個車道線來說 滑動窗口的個數nwindows = 9#設置滑動窗口的高window_height = np.int(binary_warped.shape[0]/nwindows)#設置滑動窗口的寬度==x的檢測范圍,即滑動窗口的一半margin = 100#統計圖像中非0點的個數nonzero = binary_warped.nonzero()nonzeroy = np.array(nonzero[0])#非0點的位置-x坐標序列nonzerox = np.array(nonzero[1])#非0點的位置-y坐標序列#車道檢測位置leftx_current = leftx_baserightx_current = rightx_base#設置閾值:表示當前滑動窗口中的非0點的個數minpix = 50#記錄窗口中,非0點的索引left_lane_inds = []right_lane_inds = []#遍歷滑動窗口for window in range(nwindows):# 設置窗口的y的檢測范圍,因為圖像是(行列),shape[0]表示y方向的結果,上面是0win_y_low = binary_warped.shape[0] - (window + 1) * window_height #y的最低點win_y_high = binary_warped.shape[0] - window * window_height #y的最高點# 左車道x的范圍win_xleft_low = leftx_current - marginwin_xleft_high = leftx_current + margin# 右車道x的范圍win_xright_low = rightx_current - marginwin_xright_high = rightx_current + margin# 確定非零點的位置x,y是否在搜索窗口中,將在搜索窗口內的x,y的索引存入left_lane_inds和right_lane_inds中good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &(nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &(nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]left_lane_inds.append(good_left_inds)right_lane_inds.append(good_right_inds)# 如果獲取的點的個數大于最小個數,則利用其更新滑動窗口在x軸的位置=修正車道線的位置if len(good_left_inds) > minpix:leftx_current = np.int(np.mean(nonzerox[good_left_inds]))if len(good_right_inds) > minpix:rightx_current = np.int(np.mean(nonzerox[good_right_inds]))# 將檢測出的左右車道點轉換為arrayleft_lane_inds = np.concatenate(left_lane_inds)right_lane_inds = np.concatenate(right_lane_inds)# 獲取檢測出的左右車道x與y點在圖像中的位置leftx = nonzerox[left_lane_inds]lefty = nonzeroy[left_lane_inds]rightx = nonzerox[right_lane_inds]righty = nonzeroy[right_lane_inds]# 3.用曲線擬合檢測出的點,二次多項式擬合,返回的結果是系數left_fit = np.polyfit(lefty, leftx, 2)right_fit = np.polyfit(righty, rightx, 2)return left_fit, right_fit#填充車道線之間的多邊形
def fill_lane_poly(img,left_fit,right_fit):#行數y_max = img.shape[0]#設置填充之后的圖像的大小 取到0-255之間out_img = np.dstack((img,img,img))*255#根據擬合結果,獲取擬合曲線的車道線像素位置left_points = [[left_fit[0] * y ** 2 + left_fit[1] * y + left_fit[2], y] for y in range(y_max)]right_points = [[right_fit[0] * y ** 2 + right_fit[1] * y + right_fit[2], y] for y in range(y_max - 1, -1, -1)]# 將左右車道的像素點進行合并line_points = np.vstack((left_points, right_points))# 根據左右車道線的像素位置繪制多邊形cv2.fillPoly(out_img, np.int_([line_points]), (0, 255, 0))return out_img#計算車道線曲率的方法
def cal_radius(img,left_fit,right_fit):# 比例ym_per_pix = 30/720xm_per_pix = 3.7/700# 得到車道線上的每個點left_y_axis = np.linspace(0,img.shape[0],img.shape[0]-1) #個數img.shape[0]-1left_x_axis = left_fit[0]*left_y_axis**2+left_fit[1]*left_y_axis+left_fit[0]right_y_axis = np.linspace(0,img.shape[0],img.shape[0]-1)right_x_axis = right_fit[0]*right_y_axis**2+right_fit[1]*right_y_axis+right_fit[2]# 把曲線中的點映射真實世界,再計算曲率# polyfit(x,y,n)。用多項式求過已知點的表達式,其中x為源數據點對應的橫坐標,可為行 向 量、矩陣,# y為源數據點對應的縱坐標,可為行向量、矩陣,# n為你要擬合的階數,一階直線擬合,二階拋物線擬合,并非階次越高越好,看擬合情況而定left_fit_cr = np.polyfit(left_y_axis * ym_per_pix, left_x_axis * xm_per_pix, 2)right_fit_cr = np.polyfit(right_y_axis * ym_per_pix, right_x_axis * xm_per_pix, 2)# 計算曲率left_curverad = ((1+(2*left_fit_cr[0]*left_y_axis*ym_per_pix+left_fit_cr[1])**2)**1.5)/np.absolute(2*left_fit_cr[0])right_curverad = ((1+(2*right_fit_cr[0]*right_y_axis*ym_per_pix *right_fit_cr[1])**2)**1.5)/np.absolute((2*right_fit_cr[0]))# 將曲率半徑渲染在圖像上 寫什么cv2.putText(img,'Radius of Curvature = {}(m)'.format(np.mean(left_curverad)),(20,50),cv2.FONT_ITALIC,1,(255,255,255),5)return img# 計算車道線中心的位置
def cal_line_center(img):#去畸變undistort_img = img_undistort(img,mtx,dist)#提取車道線rigin_pipeline_img = pipeline(undistort_img)#透視變換trasform_img = img_perspect_transform(rigin_pipeline_img,M)#精確定位left_fit,right_fit = cal_line_param(trasform_img)#當前圖像的shape[0]y_max = img.shape[0]#左車道線left_x = left_fit[0]*y_max**2+left_fit[1]*y_max+left_fit[2]#右車道線right_x = right_fit[0]*y_max**2+right_fit[1]*y_max+right_fit[2]#返回車道中心點return (left_x+right_x)/2# 計算中心點
def cal_center_departure(img,left_fit,right_fit):y_max = img.shape[0]left_x = left_fit[0]*y_max**2 + left_fit[1]*y_max +left_fit[2]right_x = right_fit[0]*y_max**2 +right_fit[1]*y_max +right_fit[2]xm_per_pix = 3.7/700center_depart = ((left_x+right_x)/2-lane_center)*xm_per_pix# 渲染if center_depart>0:cv2.putText(img,'Vehicle is {}m right of center'.format(center_depart), (20, 100), cv2.FONT_ITALIC, 1,(255, 255, 255), 5)elif center_depart<0:cv2.putText(img, 'Vehicle is {}m left of center'.format(-center_depart), (20, 100), cv2.FONT_ITALIC, 1,(255, 255, 255), 5)else:cv2.putText(img, 'Vehicle is in the center', (20, 100), cv2.FONT_ITALIC, 1, (255, 255, 255), 5)return img#計算車輛偏離中心點的距離
def cal_center_departure(img,left_fit,right_fit):# 計算中心點y_max = img.shape[0]#左車道線left_x = left_fit[0]*y_max**2 + left_fit[1]*y_max +left_fit[2]#右車道線right_x = right_fit[0]*y_max**2 +right_fit[1]*y_max +right_fit[2]#x方向上每個像素點代表的距離大小xm_per_pix = 3.7/700#計算偏移距離 像素距離 × xm_per_pix = 實際距離center_depart = ((left_x+right_x)/2-lane_center)*xm_per_pix# 渲染if center_depart>0:cv2.putText(img,'Vehicle is {}m right of center'.format(center_depart), (20, 100), cv2.FONT_ITALIC, 1,(255, 255, 255), 5)elif center_depart<0:cv2.putText(img, 'Vehicle is {}m left of center'.format(-center_depart), (20, 100), cv2.FONT_ITALIC, 1,(255, 255, 255), 5)else:cv2.putText(img, 'Vehicle is in the center', (20, 100), cv2.FONT_ITALIC, 1, (255, 255, 255), 5)return img#圖片處理流程匯總 方便視頻調用
def process_image(img):# 圖像去畸變undistort_img = img_undistort(img,mtx,dist)# 車道線檢測rigin_pipline_img = pipeline(undistort_img)# 透視變換transform_img = img_perspect_transform(rigin_pipline_img,M)# 擬合車道線left_fit,right_fit = cal_line_param(transform_img)# 繪制安全區域result = fill_lane_poly(transform_img,left_fit,right_fit)#轉換回原來的視角transform_img_inv = img_perspect_transform(result,M_inverse)# 曲率和偏離距離transform_img_inv = cal_radius(transform_img_inv,left_fit,right_fit)#偏離距離transform_img_inv = cal_center_departure(transform_img_inv,left_fit,right_fit)#附加到原圖上transform_img_inv = cv2.addWeighted(undistort_img,1,transform_img_inv,0.5,0)#返回處理好的圖像return transform_img_invif __name__ == "__main__":ret, mtx, dist, rvecs, tvecs = cal_calibrate_params(file_paths)#透視變換#獲取原圖的四個點img = cv2.imread('./test/straight_lines2.jpg')points = [[601, 448], [683, 448], [230, 717], [1097, 717]]#將四個點繪制到圖像上 (文件,坐標起點,坐標終點,顏色,連接起來)img = cv2.line(img, (601, 448), (683, 448), (0, 0, 255), 3)img = cv2.line(img, (683, 448), (1097, 717), (0, 0, 255), 3)img = cv2.line(img, (1097, 717), (230, 717), (0, 0, 255), 3)img = cv2.line(img, (230, 717), (601, 448), (0, 0, 255), 3)#透視變換的矩陣M,M_inverse = cal_perspective_params(img,points)#計算車道線的中心距離lane_center = cal_line_center(img)# 視頻處理clip1 = VideoFileClip("./project_video.mp4")white_clip = clip1.fl_image(process_image)white_clip.write_videofile("./output.mp4", audio=False)
總結
以上是生活随笔為你收集整理的智慧交通day03-车道线检测实现09:车道线检测代码汇总(Python3.8)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql命令导入导出数据库_MYSQL
- 下一篇: java excel 模板 替换_JAV