python实现基于HOG+SVM的行人检测算法代码
时间: 2023-08-12 12:06:12 浏览: 132
以下是一个基于Python实现HOG+SVM行人检测算法的代码示例:
```python
import cv2
import numpy as np
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
# 收集行人数据集
pos_images = ['pos1.jpg', 'pos2.jpg', 'pos3.jpg', ...]
neg_images = ['neg1.jpg', 'neg2.jpg', 'neg3.jpg', ...]
# 提取HOG特征
hog = cv2.HOGDescriptor()
features = []
labels = []
for image_path in pos_images:
img = cv2.imread(image_path)
hog_feature = hog.compute(img)
features.append(hog_feature)
labels.append(1)
for image_path in neg_images:
img = cv2.imread(image_path)
hog_feature = hog.compute(img)
features.append(hog_feature)
labels.append(-1)
features = np.array(features)
labels = np.array(labels)
# 训练SVM分类器
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)
svm = SVC(kernel='linear')
svm.fit(X_train, y_train)
# 行人检测
img = cv2.imread('test.jpg')
win_size = (64, 128)
block_size = (16, 16)
block_stride = (8, 8)
cell_size = (8, 8)
nbins = 9
for i in range(0, img.shape[0]-win_size[1], block_stride[1]):
for j in range(0, img.shape[1]-win_size[0], block_stride[0]):
win = img[i:i+win_size[1], j:j+win_size[0]]
hog_feature = hog.compute(win, winStride=(8,8), padding=(0,0))
pred = svm.predict(hog_feature.reshape(1, -1))
if pred == 1:
cv2.rectangle(img, (j, i), (j+win_size[0], i+win_size[1]), (0, 255, 0), 2)
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
该代码中,我们首先使用OpenCV中的HOGDescriptor函数对收集到的行人数据集中的图片进行HOG特征提取,并将提取的HOG特征和对应的标签存储在features和labels数组中。然后使用sklearn库中的train_test_split函数将数据集划分为训练集和测试集,并使用SVC模型进行训练。最后使用滑动窗口对测试图片进行行人检测,并将检测到的行人框标记出来。
阅读全文