优达学城无人驾驶工程师——P5车辆检测功能

本文详细介绍了优达学城无人驾驶工程师课程中的P5阶段,重点聚焦于车辆检测功能。通过导入相关库,利用HOG方法提取车辆特征,并对比有车与无车图像的空间差异。此外,文章还演示了如何读取图像,提取特征向量,并应用滑动窗口技术进行车辆检测。所有资源及样本图片可在提供的GitHub链接中获取。
摘要由CSDN通过智能技术生成

这次讲的是优达学城无人驾驶工程师第一期的最后一个项目,车辆检测功能,代码如下。

导包

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
  • 4
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值