Search code examples
javaimagemasksobel

Sobel Operator MaskX


Why my image quality after masking x get worse?

public void doMaskX() {
    int[][] maskX = { { -1, -2, -1 }, { 0, 0, 0 }, { 1, 2, 1 } };

    int rgb, alpha = 0;
    int[][] square = new int[3][3];

    for (int y = 0; y < width - 3; y++) {
        for (int x = 0; x < height - 3; x++) {
            int sum = 0;
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {
                    rgb = imgx.getRGB(y + i, x + j);

                    alpha = (rgb >> 24) & 0xff;
                    int red = (rgb >> 16) & 0xff;
                    int green = (rgb >> 8) & 0xff;
                    int blue = rgb & 0xff;

                    square[i][j] = (red + green + blue)/3;
                    sum += square[i][j] * maskX[i][j];
                }
            }
            rgb = (alpha << 24) | (sum << 16) | (sum << 8) | sum;
            imgx.setRGB(y, x, rgb);

        }
    }
    writeImg();
}

this is an image before masking

And this is the image after masking

the quality should be better of second image and why is yellow color appears?


Solution

  • It is important to realize that you are computing the intensity of the gradient here and that is what you are displaying. Therefore the intensity (or magnitude) is a positive number. You have to take the absolute value:

    sum=Math.abs(sum);
    

    If you take the y derivative also then you can combine:

    sum=Math.sqrt(sumx*sumx+sumy*sumy);