HOG+SVM这种目标检测的方法是比较早期的基于机器学习模型构建的目标检测方法,事实证明:他很有效,最早期的时候解决了很多的问题,随着深度学习的发展,算力、数据和算法的快速迭代更新,越来越多的目标检测需求都开始基于深度学习来构建算法模型了,在我的目标检测专栏里面介绍了很多不用场景的检测应用,本文主要是实践HOG+RF的组合方法来实现目标检测,其实,在这种组合模式中,HOG扮演的就是特征提取算子,RF也好,SVM也好扮演的就是级联分类器。
在之前的文章中,我已经做过相关的工作了,只不过做的是行人检测,感兴趣的话可以看下:
Python基于HOG+SVM/RF/DT等模型实现目标检测[行人检测]
首先看下数据集:
【neg】
【pos】
正样本的数据量比较少,只有50张,在创建对应的负样本数据集的时候我有意创建少了点,达到了100张。
有了前文的基础,这里就不再赘述了,同样先抽取所要的特征:
def img2Feature(dataDir="data/",save_path="feature.json"):
"""
特征提取计算
"""
feature=[]
for one_label in os.listdir(dataDir):
print("one_label: ", one_label)
oneDir=dataDir+one_label+'/'
for one_pic in os.listdir(oneDir):
one_path=oneDir+one_pic
print("one_path: ", one_path)
#加载图像
one_img = imread(one_path, as_gray=True)
one_vec = hog(one_img, orientations=orientations, pixels_per_cell=pixels_per_cell, cells_per_block=cells_per_block,
visualize=visualize, block_norm=normalize)
one_vec=one_vec.tolist()
one_vec.append(one_label)
feature.append(one_vec)
print("feature_length: ", len(feature))
with open(save_path,"w") as f:
f.write(json.dumps(feature))
这里训练分类器模型我用的是随机森林模型,如下:
def RFModel(data="feature.json", rationum=0.30, model_path="RF.pkl"):
"""
随机森林
"""
with open(data) as f:
data_list = json.load(f)
x_list = [one[:-1] for one in data_list]
y_list = [one[-1] for one in data_list]
print("y_list: ", list(set(y_list)))
X_train, X_test, y_train, y_test = split_data(x_list, y_list, ratio=rationum)
RF = RandomForestClassifier(n_estimators=100)
RF.fit(X_train, y_train)
y_pred = RF.predict(X_test)
print("RF model accuracy: ", RF.score(X_test, y_test))
# 指标计算
res_dict = {}
Precision, Recall, F1 = calThree(y_test, y_pred)
res_dict["precision"] = Precision
res_dict["recall"] = Recall
res_dict["F1"] = F1
res_dict["accuracy"] = F1
print("res_dict: ", res_dict)
saveModel(RF, save_path=model_path)
return res_dict
得到训练好的模型之后,就可以进行测试了,如下所示:
整体还是不错的,虽然跟深度学习效果相比有差距,但是毕竟训练样本很少,能达到这样的效果已经是不错的了。



