opencv-100-HOG特征与行人检测

知识点

HOG(Histogram of Oriented Gradient)特征在对象识别与模式匹配中是一种常见的特征提取算法,是基于本地像素块进行特征直方图提取的一种算法,对象局部的变形与光照影响有很好的稳定性,最初是用HOG特征来来识别人像,通过HOG特征提取+SVM训练,可以得到很好的效果,OpenCV已经有了。

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv) {
Mat src = imread("D:/images/pedestrian.png");
if (src.empty()) {
printf("could not load image..\n");
return -1;
}
imshow("input", src);
HOGDescriptor *hog = new HOGDescriptor();
hog->setSVMDetector(hog->getDefaultPeopleDetector());
vector<Rect> objects;
hog->detectMultiScale(src, objects, 0.0, Size(4, 4), Size(8, 8), 1.25);
for (int i = 0; i < objects.size(); i++) {
rectangle(src, objects[i], Scalar(0, 0, 255), 2, 8, 0);
}
imshow("result", src);
waitKey(0);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
"""
HOG特征与行人检测
"""

import cv2 as cv

src = cv.imread("images/pedestrian.png")
hog = cv.HOGDescriptor()
hog.setSVMDetector(cv.HOGDescriptor_getDefaultPeopleDetector())
# detect people in image
(rects, weights) = hog.detectMultiScale(src, winStride=(4, 4),
padding=(8, 8), scale=1.25,
useMeanshiftGrouping=False)

for (x, y, w, h) in rects:
cv.rectangle(src, (x, y), (x + w, y + h), (0, 255, 0), 2)

cv.imshow("hog-detector", src)

cv.waitKey(0)
cv.destroyAllWindows()

结果

代码地址

github