Cole Jacob Wandler
Cole Jacob Wandler

Reputation: 3

how to calculate image gradient

My instructor gave us the pseudocode:

grad = abs(im(x+1,y)-im(x-1,y)) + abs(im(x,y+1)-im(x,y-1))

to calculate the gradient of an image for an edge detector we are making. I thought that the way this pseudocode would look like is:

int grad = Math.abs(img.getRGB(i+1,j)-img.getRGB(i-1,j)) + 
           Math.abs(img.getRGB(i,j+1)-img.getRGB(i,j-1));

he said this code would only get the R value of a color. I'm having trouble understanding this. Could someone help me understand how to use this formula to get an entire color gradient? (this formula would go in a nested for loop and apply to every pixel)

Upvotes: 0

Views: 3028

Answers (1)

pickypg
pickypg

Reputation: 22332

Your instructor means that you need to get the Red for each pixel. You can either fiddle with the bits that are returned from getRGB(x, y) to get just the red, or you can put the RGB value into a Color and extract it that way.

public int getRed(BufferedImage image, int x, int y)
{
    // Color color = new Color(image.getRGB(x, y), true); if you care about alpha
    Color color = new Color(image.getRGB(x, y));

    return color.getRed();
}

This will give you a value between [0, 255]. If you want a value between [0, 1], then you need to divide by 255.0.

Bit shifting would be a faster solution, but this is the easier solution and it is likely fast enough. For reference, red would be bits [16, 23].

Upvotes: 1

Related Questions