繁体   English   中英

Sobel运算符不适用于矩形图像

[英]Sobel operator doesn't work with rectangle images

我尝试在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时,结果图像将被破坏,并且有一些对角的黑线。 :\\

例:

在此处输入图片说明

结果:

在此处输入图片说明

您的代码似乎期待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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM