Search code examples
matlabimage-processingcomputer-visionfeature-descriptor

How to calculate signed and unsigned Gradient orientations in Matlab


When calculating the gradient orientation for using it in HOG descriptor extraction, we can either choose to use gradient orientations between 0-180 or 0-360, how can we produce such angles using Matlab? i have the following code:

Im=imread('cameraman.tif'); // reading the image
Im=double(Im);  // converting it to double
hx = [-1,0,1];  // the gradient kernel for x direction
hy = -hx;      // the gradient kernel for y direction
grad_x = imfilter(Im,hx);   //gradient image in x direction
grad_y = imfilter(Im,hy);   // gradient image in y direction

% angles in 0-180:
...
%angles in 0-360:
...

Solution

  • Usually you can use atan2 to generate angles that are between -180 and 180 given your horizontal and vertical gradient components, and hence signed angles. However, if you want angles from 0 to 360 or unsigned angles, all you have to do is search for any angles that are generated by atan2 that are negative, and add 360 to each angle. This will allow you to get the angle between [0,360). For example, an angle of -5 degrees is actually 355 degrees unsigned. Therefore:

    angles = atan2(grad_y, grad_x); %// Signed
    angles(angles < 0) = 2*pi + angles(angles < 0); %// Unsigned
    

    Here atan2 is in radians, so we add 2*pi instead of 360 degrees. If you'd like degrees instead of radians, use the equivalent degrees call: atan2d and therefore:

    angles = atan2d(grad_y, grad_x); %// Signed
    angles(angles < 0) = 360 + angles(angles < 0); %// Unsigned
    

    Going with your comments, you would also like to do the reverse. Basically, if we are given an unsigned angle, how do we go to a signed angle? Simply do the opposite. Find all angles that are > 180, then take this angle and subtract by 360. For example, an angle of 182 unsigned is -178 signed, or 182 - 360 = -178.

    Therefore:

    Radians

    angles(angles > pi) = angles(angles > pi) - (2*pi); 
    

    Degrees

    angles(angles > 180) = angles(angles > 180) - 360;