【问题标题】:Sobel operator doesn't work with rectangle imagesSobel 运算符不适用于矩形图像
【发布时间】:2015-09-19 12:18:39
【问题描述】:

我尝试在 Java 中实现 Sobel 运算符,但结果只是一些像素混合。

    int i, j;
    FileInputStream inFile = new FileInputStream(args[0]);
    BufferedImage inImg = ImageIO.read(inFile);
    int width = inImg.getWidth();
    int height = inImg.getHeight();
    int[] output = new int[width * height];
    int[] pixels = inImg.getRaster().getPixels(0, 0, width, height, (int[])null);

    double Gx;
    double Gy;
    double G;

    for(i = 0 ; i < width ; i++ )
    {
        for(j = 0 ; j < height ; j++ )
        {
            if (i==0 || i==width-1 || j==0 || j==height-1)
                G = 0;
            else{
                Gx = pixels[(i+1)*height + j-1] + 2*pixels[(i+1)*height +j] + pixels[(i+1)*height +j+1] -
                        pixels[(i-1)*height +j-1] - 2*pixels[(i-1)*height+j] - pixels[(i-1)*height+j+1];
                Gy = pixels[(i-1)*height+j+1] + 2*pixels[i*height +j+1] + pixels[(i+1)*height+j+1] -
                        pixels[(i-1)*height+j-1] - 2*pixels[i*height+j-1] - pixels[(i+1)*height+j-1];
                G  = Math.hypot(Gx, Gy);
            }

            output[i*height+j] = (int)G;
        }
    }


    BufferedImage outImg = new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);
    outImg.getRaster().setPixels(0,0,width,height,output);
    FileOutputStream outFile = new FileOutputStream("result.jpg");
    ImageIO.write(outImg,"JPG",outFile);

    JFrame TheFrame = new JFrame("Result");

    JLabel TheLabel = new JLabel(new ImageIcon(outImg));
    TheFrame.getContentPane().add(TheLabel);

    TheFrame.setSize(width, height);

    TheFrame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
    TheFrame.setVisible(true);

它适用于方形图像,但当 width != height 时,结果图像被破坏并且有一些对角黑线。 :\

例子:

结果:

【问题讨论】:

    标签: java sobel


    【解决方案1】:

    您的代码似乎期望Raster.getPixels中产生结果,如下所示:

    0  3  6
    1  4  7
    2  5  8
    

    但我相信它实际上是按行执行的,如下所示:

    0  1  2
    3  4  5
    6  7  8
    

    所以基本上,你目前有这样的东西:

    pxy = pixels[x * height + y];
    

    你应该有

    pxy = pixels[y * width + x];
    

    例如,你有:

    pixels[(i+1)*height + j-1]
    

    你想要的

    pixels[(j-1)*width + i-1]
    

    【讨论】:

    • 我做了这个更改,但它仍然是错误的。结果不同,但也像噪音。
    • @micobg:我怀疑你当时并没有非常一致地做出改变。如果你错过了一个计算,你就会遇到问题。它仍然适用于方形图片吗?
    • 我工作! :) 非常感谢!我用于测试的图片不是灰度的。 Whit grayscape 图像效果很好。
    猜你喜欢
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 2015-08-02
    • 2017-09-08
    • 2018-02-24
    • 2018-08-20
    相关资源
    最近更新 更多