文章目录
- HOG特征描述子
- 算法演示
HOG特征描述子
OpenCV—Python HOG方向梯度直方图
提取流程
- 灰度图像转换,标准化gamma空间和颜色空间
- 梯度计算,使用sobel算子
- 分网格的梯度方向直方图(8x8像素cell)
- 块描述子,定义(2X2cell=block)
- 块描述子归一化
- 得到HOG特征向量
cell梯度
- 特征数据与检测窗口
- 匹配方法
关于算法详情:
查看 https://zhuanlan.zhihu.com/p/40960756 或者 https://zhuanlan.zhihu.com/p/75538637 或者 https://zhuanlan.zhihu.com/p/85829145
特征数据与检测窗口
- 最终获得HOG描述算子(特征数据)
- 需要正向训练200个左右的特征样本
- 反向训练600~800个左右的特征样本
- 初步测试、开窗检测
对于64x128的像素块,可以分为8x16个Cell分为7x15个块(R-HOG)
总计的直方图向量数为:7x15x2x2x9 = 3780个向量数组
算法演示
头文件 image_feature_all.h
:声明类与公共函数
#pragma once
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
class ImageFeature {
public:
void hog_demo(Mat& image);
};
主函数main.cpp
调用该类的公共成员函数
#include "image_feature_all.h"
int main(int argc, char** argv) {
const char* img_path = "D:\\Desktop\\jianzhu.jpg";
Mat image = imread(img_path, IMREAD_GRAYSCALE); //灰度图读入
if (image.empty()) {
cout << "图像数据为空,读取文件失败!" << endl;
}
ImageFeature imgfeature;
imgfeature.hog_demo(image);
imgfeature.sift_demo(image);
imshow("image", image);
waitKey(0);
destroyAllWindows();
return 0;
}
源文件 feature_extract.cpp
:实现类与公共函数
void ImageFeature::hog_demo(Mat& image) {
Mat gray_src;
cvtColor(image, gray_src, COLOR_BGR2GRAY);
// 生成自定义HOG特征向量
/*
Mat dst;
resize(image, dst, Size(64, 128));
HOGDescriptor detector(Size(64, 128), Size(16, 16), Size(8, 8), Size(8, 8), 9);
vector<float> detectors;
vector<Point> locations;
detector.compute(dst, detectors, Size(0, 0), Size(0, 0), locations);
cout << "Number of HOG detectors.size() = " << detectors.size() << endl;
*/
// 使用默认行人检测算子
HOGDescriptor hog = HOGDescriptor();
hog.setSVMDetector(hog.getDefaultPeopleDetector());
vector<Rect> foundLocations;
Mat resultImg = image.clone();
hog.detectMultiScale(gray_src, foundLocations, 0, Size(8, 8), Size(32, 32), 1.05, 2.0, false);
for (size_t i = 0; i < foundLocations.size(); i++){
rectangle(resultImg, foundLocations[i], Scalar(0, 0, 255), 1, 8, 0);
}
imshow("HOG SVM Detector", resultImg);
}