Sobel operator doesn't work with rectangle images
I try to implement Sobel operator in Java but the result is just some mix of pixels.
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);
It works great with square images but when width != height the result image is broken and there are some diagonal black lines. :
Example:
Result:
Your code appears to expect Raster.getPixels
to produce a result in columns, like this:
0 3 6
1 4 7
2 5 8
But I believe it actually does it in rows, like this:
0 1 2
3 4 5
6 7 8
So basically, where you currently have something like:
pxy = pixels[x * height + y];
you should have
pxy = pixels[y * width + x];
So for example, where you have:
pixels[(i+1)*height + j-1]
you want
pixels[(j-1)*width + i-1]
链接地址: http://www.djcxy.com/p/72516.html
上一篇: 任何等同于GCC的MSVC'
下一篇: 索贝尔操作符不适用于矩形图像