hog特征提取matlab代码
时间: 2023-11-20 22:03:15 浏览: 157
以下是使用MATLAB提取HOG特征的示例代码。假设有一张图像img,图像大小为[height,width],并且希望将图像划分为n个单元格。
```matlab
% 定义参数
cellSize = 8; % 单元格大小
numBins = 9; % 直方图方向数
height = size(img,1);
width = size(img,2);
% 计算梯度
I = rgb2gray(img);
Ix = conv2(I,[-1 0 1],'same');
Iy = conv2(I,[-1;0;1],'same');
grad = sqrt(Ix.^2 + Iy.^2);
angle = atan2(Iy,Ix);
% 将角度转化为0-180度
angle(angle<0) = angle(angle<0) + pi;
% 将图像划分为单元格
numHorzCells = floor(width/cellSize);
numVertCells = floor(height/cellSize);
histograms = zeros(numVertCells,numHorzCells,numBins);
% 计算每个单元格的直方图
for i=1:numVertCells
for j=1:numHorzCells
rowStart = (i-1)*cellSize+1;
rowEnd = i*cellSize;
colStart = (j-1)*cellSize+1;
colEnd = j*cellSize;
histogram = zeros(numBins,1);
for m=rowStart:rowEnd
for n=colStart:colEnd
bin = floor(numBins*angle(m,n)/pi)+1;
histogram(bin) = histogram(bin) + grad(m,n);
end
end
histograms(i,j,:) = histogram;
end
end
% 将每个单元格的直方图拼接为特征向量
features = reshape(histograms,[],numBins);
features = bsxfun(@rdivide,features,sum(features,2)+eps);
features = sqrt(features);
features = bsxfun(@rdivide,features,norm(features)+eps);
```
其中,bsxfun函数是一种广播函数,用于处理两个具有不同大小的矩阵之间的操作。
阅读全文