0

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);

正方形の画像ではうまく機能しますが、幅 != 高さの場合、結果の画像は壊れており、斜めの黒い線がいくつかあります。:\

例:

ここに画像の説明を入力

結果:

ここに画像の説明を入力

4

1 に答える 1

3

あなたのコードは、次のようにcolumnsRaster.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]
于 2015-07-02T06:07:35.020 に答える