function H = computeHOG(magnitudes, orientations)
% computeHOG Computes a HOG for the supplied gradient vectors.
% H = getHistogram(magnitudes, orientations)
%
% This function takes the supplied gradient vectors and places them into a
% histogram with 9 based on their unsigned orientation.
%
% Each gradient vector's magnitude is split between the two nearest bins,
% in proportion to the distance between the two nearest bin centers.
%
% A gradient's contribution to the histogram is equal to its magnitude;
% the magnitude is divided between the two nearest bin centers.
%
% Parameters:
% magnitudes - A matrix of the magnitudes of the gradient vectors
% orientations - A matrix storing the orientations in degrees of the
% gradient vectors (ranging from -180 to 180)
% Returns:
% A vector of length 9 containing the histogram.
% Make the orientations unsigned by adding pi (180 degrees) to all negative orientations.
orientations(orientations < 0) = orientations(orientations < 0) + 180;
%binEdges=0:20:180;
binCenters=10:20:180;
% The gradient angle for each pixel will fall between two bin centers.
% For each pixel, we split the bin contributions between the bin to the left
% and the bin to the right based on how far the angle is from the bin centers.
% Replace index 0 with 9 and index 10 with 1.
leftBinIndex = round(orientations/20);
rightBinIndex = leftBinIndex + 1;
leftBinIndex(leftBinIndex == 0) = 9;
rightBinIndex(rightBinIndex == (10)) = 1;
% For each pixel, find the center of the left bin
leftBinCenter = binCenters(leftBinIndex);
% For each pixel, compute the fraction of the magnitude to contribute to
% left and right bins
rightPortions =orientations - leftBinCenter;
rightPortions(rightPortions<0)=rightPortions(rightPortions<0)+180;
rightPortions=rightPortions/20;
leftPortions = 1 - rightPortions;
% Create histogram: left bin - left portions of magnitude, etc.
H = accumarray(leftBinIndex(:),leftPortions(:).*magnitudes(:));
H = H + accumarray(rightBinIndex(:),rightPortions(:).*magnitudes(:));
end