Frank
Frank

Reputation: 33

Gradient histograms in matlab

I am trying to figure out how to create an array of histogram to compare the magnitude and direction of gradient vectors of an image in matlab. I am to use sobel masks to find the gradients, so far I have:

sobel_x = [-1 -2 -1;0  0  0;1  2  1];
sobel_y = [-1  0  1;-2  0  2;-1  0  1];

gx = filter2(sobel_x,im,'same');
gy = filter2(sobel_y,im,'same');

Now I need to figure out how to create a histogram to compare it with other images.

Upvotes: 3

Views: 4577

Answers (1)

salgarcia
salgarcia

Reputation: 517

You can take the computed gx and gy matrices and treat them as long vectors, then group them into a gradient vector that is size: 2 x (# number of elements in gx or gy)

% create the gradient vectors
    grad_vector(1,:) = gx(:);
    grad_vector(2,:) = gy(:);

then you can find the magnitude and direction of each gradient vector in a variety of ways, for example:

%find magnitude and direction of each gradient vector
    for i=1:size(grad_vector,2);
       magn(i) = norm(grad_vector(:,i));
       dir(i) = atand(grad_vector(2,i)/grad_vector(1,i));
    end

the histogram can then be created by deciding how to divide up the results into a number of bins. For example, you may choose to divide the direction into 4 bins and the magnitude into 3, then:

% find histograms, dividing into appropriate bins
    histdir = hist(dir,4);
    histmag = hist(magn,3);

Upvotes: 6

Related Questions