智慧交通day03-车道线检测实现07:车道曲率和中心点偏离距离计算+代码实现
生活随笔
收集整理的這篇文章主要介紹了
智慧交通day03-车道线检测实现07:车道曲率和中心点偏离距离计算+代码实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
學習目標
- 知道車道曲率計算的方法
- 知道計算中心點偏離距離的計算
1.曲率的介紹
曲線的曲率就是針對曲線上某個點的切線方向角對弧長的轉動率,通過微分來定義,表明曲線偏離直線的程度。數學上表明曲線在某一點的彎曲程度的數值。曲率越大,表示曲線的彎曲程度越大。曲率的倒數就是曲率半徑。
1.1.圓的曲率
下面有三個球體,網球、籃球、地球,半徑越小的越容易看出是圓的,所以隨著半徑的增加,圓的程度就越來越弱了。
定義球體或者圓的“圓”的程度,就是 曲率 ,計算方法為:
其中rr為球體或者圓的半徑,這樣半徑越小的圓曲率越大,直線可以看作半徑為無窮大的圓,其曲率為:
1.2.曲線的曲率
不同的曲線有不同的彎曲程度:
?
怎么來表示某一條曲線的彎曲程度呢?
我們知道三點確定一個圓:
當δ??趨近于0時,我們可以的到曲線在x_0x?0??處的密切圓,也就是曲線在該點的圓近似:
另,在曲線比較平坦的位置,密切圓較大,在曲線比較彎曲的地方,密切圓較小,
因此,我們通過密切圓的曲率來定義曲線的曲率,定義如下:
2.實現
計算曲率半徑的方法,代碼實現如下:
def cal_radius(img, left_fit, right_fit):# 圖像中像素個數與實際中距離的比率# 沿車行進的方向長度大概覆蓋了30米,按照美國高速公路的標準,寬度為3.7米(經驗值)ym_per_pix = 30 / 720 # y方向像素個數與距離的比例xm_per_pix = 3.7 / 700 # x方向像素個數與距離的比例# 計算得到曲線上的每個點left_y_axis = np.linspace(0, img.shape[0], img.shape[0] - 1)left_x_axis = left_fit[0] * left_y_axis ** 2 + left_fit[1] * left_y_axis + left_fit[2]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]# 獲取真實環境中的曲線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曲率半徑顯示效果:
計算偏離中心的距離:
# 1. 定義函數計算圖像的中心點位置 def cal_line__center(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)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# 2. 假設straight_lines2_line.jpg,這張圖片是位于車道的中央,實際情況可以根據測量驗證. img =cv2.imread("./test/straight_lines2_line.jpg") lane_center = cal_line__center(img) print("車道的中心點為:{}".format(lane_center))# 3. 計算偏離中心的距離 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計算偏離中心顯示效果如下:
總結
總代碼匯總:
# encoding:utf-8from matplotlib import font_manager my_font = font_manager.FontProperties(fname="/System/Library/Fonts/PingFang.ttc")import cv2 import numpy as np import matplotlib.pyplot as plt #遍歷文件夾 import glob from moviepy.editor import VideoFileClip import sys reload(sys) sys.setdefaultencoding('utf-8')"""參數設置""" 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_readius(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]# 把曲線中的點映射真實世界,再計算曲率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)/2def 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 imgif __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)
?
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的智慧交通day03-车道线检测实现07:车道曲率和中心点偏离距离计算+代码实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python notebooks_Jup
- 下一篇: java cygwin 乱码_windo