这次讲的是优达学城无人驾驶工程师第一期的最后一个项目,车辆检测功能,代码如下。
导包
import cv2
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.image as mpimg
%matplotlib inline
import os
import glob
from skimage.feature import hog
import seaborn as sns
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC
import time
from sklearn.cross_validation import train_test_split
from scipy.ndimage.measurements import label
读取图片
#读取图片
cars = []
notcars = []
car_paths = ['vehicles/GTI_Far', 'vehicles/GTI_Left', 'vehicles/GTI_Right', 'vehicles/GTI_MiddleClose', 'vehicles/GTI_KITTI_extracted']
for path in car_paths:
path_new = os.path.join(path,"*.png")
for infile in glob.glob(path_new):
cars.append(infile)
notcar_paths = ['non-vehicles/GTI', 'non-vehicles/Extras']
for path in notcar_paths:
path_new = os.path.join(path,"*.png")
for infile in glob.glob(path_new):
notcars.append(infile)
后面会用到的函数
#定义一些提取特征的函数
def bin_spatial_features(img,size = (32,32)):
features = cv2.resize(img,size).ravel()
#将多维数据降成一维
return features
def get_hog_features(img,orient,pix_per_cell,cell_per_block,vis = False,feature_vec = True):
if vis == True:
features,hog_image = hog(img,orientations=orient,pixels_per_cell=(pix_per_cell,pix_per_cell),
cells_per_block = (cell_per_block,cell_per_block),transform_sqrt = False,
visualise = vis,feature_vector = feature_vec)
return features,hog_image
else:
features = hog(img,orientations=orient,pixels_per_cell=(pix_per_cell,pix_per_cell),
cells_per_block = (cell_per_block,cell_per_block),transform_sqrt = False,
visualise = vis,feature_vector = feature_vec)
return features
def extract_featrues_hog(imgs,cspace = 'RGB',orient = 9,pix_per_cell = 8,cell_per_block = 2,hog_channel = 0):
#创建一个特征向量列表
features = []
#迭代列表中的图片
for img in imgs:
image = cv2.imread(img)
image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)#变成RGB格式
#实现多种颜色转换
if cspace != 'RGB':
if cspace == 'HSV':
feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
elif cspace == 'LUV':
feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2LUV)
elif cspace == 'HLS':
feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)
elif cspace == 'YUV':
feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YUV)
elif cspace == 'YCrCb':
feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YCrCb)
else: feature_image = np.copy(image)
if hog_channel == 'ALL':
hog_features = []
for channel in range(feature_image.shape[2]):
hog_features.append(get_hog_features(feature_image[:,:,channel],orient,pix_per_cell,cell_per_block,vis = False))
hog_features = np.ravel(hog_features)
else:
hog_features = get_hog_features(feature_image[:,:,hog_channel],orient,pix_per_cell,cell_per_block,vis = False)
features.append(hog_features)
return features
def color_hist_features(img,nbins = 32,bins_range = (0,255)):
#计算颜色直方图
channel1_hist = np.histogram(img[:,:,0],bins=nbins,range=bins_range)
channel2_hist = np.histogram(img[:,:,1],bins=nbins,range=bins_range)
channel3_hist = np.histogram(img[:,:,2],bins=nbins,range=bins_range)
#合并
hist_features = np.concatenate((channel1_hist[0],channel2_hist[0],channel3_hist[0]))
return hist_features
下面是展示HOG提取车辆特征
#特征值设置 pix_per_cell = [8,16,8,16] cell_per_block = [1,1,2,2] orient = [9,9,9,9] for i in range(len(pix_per_cell)): car_number = 1167 car_image = cv2.imread(cars[car_number]) gray = cv2.cvtColor(car_image,cv2.COLOR_BGR2GRAY) features , hog_image = get_hog_features(gray,orient[i],pix_per_cell[i],cell_per_block[i],vis=True,feature_vec=False) feature_flatten = features.ravel() with sns.axes_style('white'): fig = plt.figure() plt.subplot(121) plt.imshow(car_image,cmap = 'gray') plt.title('original image') plt.subplot(122) plt.imshow(hog_i