我为Sobel运算符编写了一个用于边缘检测的类,但是当我使用示例图像时,我的边缘关闭了。如果有人可以帮助我,我将非常感激。

import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.awt.image.Raster;
import java.util.Arrays;

class SobelFilter {

private static final float[] sobel1 = { 1.0f, 0.0f, -1.0f};
private static final float[] sobel2 = { 1.0f, 2.0f,  1.0f};
private static final boolean[] sobelBoolean = {true, false};

private SobelFilter() {}

private static ConvolveOp getSobelX(boolean fs) {
    Kernel kernel = null;

    if (fs) {
        kernel = new Kernel(1, 3, sobel1);
    }
    else {
        kernel = new Kernel(3, 1, sobel2);
    }

    return new ConvolveOp(kernel, ConvolveOp.EDGE_ZERO_FILL, null);
}

private static ConvolveOp getSobelY(boolean fs) {
    Kernel kernel = null;

    if (fs) {
        kernel = new Kernel(1, 3, sobel2);
    }
    else {
        kernel = new Kernel(3, 1, sobel1);
    }

    return new ConvolveOp(kernel, ConvolveOp.EDGE_ZERO_FILL, null);
}

public static BufferedImage getSobelFilter(BufferedImage img) {
    int width = img.getWidth();
    int height = img.getHeight();
    int size = width * height;
    int[] x = new int[size];
    int[] y = new int[size];
    int[] pixelM = new int[size];
    //double[] pixelD = new double[size];

    BufferedImage sobelX = null;
    BufferedImage sobelY = null;

    for(boolean i : sobelBoolean) {
        sobelX = getSobelX(i).filter(img, null);
        sobelY = getSobelY(i).filter(img, null);
    }

    sobelX.getRaster().getPixels(0, 0, width, height, x);
    sobelY.getRaster().getPixels(0, 0, width, height, y);

    for(int i = 0; i < size; i++) {
        pixelM[i] = (int) Math.hypot(x[i], y[i]);
        //pixelD[i] = Math.atan2((double) y[i], (double) x[i]);
    }

    BufferedImage result =
        new BufferedImage(width, height,
                          BufferedImage.TYPE_BYTE_GRAY);
    result.getRaster().setPixels(0, 0, width, height, pixelM);

    return result;
}
}
我以Wikipedia中的阀门图片为例。
原始测试图片

预期结果

实际结果

最佳答案

您绘制的是渐变的Y分量。考虑一下:

g2.drawImage(sobelX, null, 0, 0);
g2.drawImage(sobelY, null, 0, 0);
sobelX隐藏在sobelY后面,因此您只能看到后者。

您想要的是渐变的范数。您必须扫描两个图像并为z = sqrt(x*x + y*y)的每个像素x及其对应的sobelXy计算sobelY

伪代码:
norm = image of the same size of sobelX and sobelY;

for (int x = 0; x < horizontal dimension of the image; ++x) {
    for (int y = 0; y < vertical dimension of the image; ++y) {
        xPixel = sobelX.pixelAt(x,y);
        yPixel = sobelY.pixelAt(x,y);
        norm.pixelAt(x,y) = Math.hypot(xPixel, yPixel);
    }
}

return norm;

09-26 15:04