我想实现Sobel
算法。
我获取输入图像的灰色数据并将数据放入mGrayData
:
BufferedImage mImage, mNewImage;
for (int i = 0; i < mHeight; i++) {
for (int j = 0; j < mWidth; j++) {
int rgb = mImage.getRGB(j, i);
int newRgb;
int r = (rgb >> 16) & 0xff;
int g = (rgb >> 8) & 0xff;
int b = rgb & 0xff;
int grayLevel = (r + g + b) / 3;
int gray = (grayLevel << 16) + (grayLevel << 8) + grayLevel;
mGrayData[i * mWidth + j] = gray;
}
}
我计算每个点的渐变:
int[] gradient = new int[mWidth * mHeight];
for (int x=1;x<mWidth-1;x++){
for (int y=1;y<mHeight-1;y++){
int grayX = getGrayPoint(x+1,y-1)+2*getGrayPoint(x+1,y)+getGrayPoint(x+1,y+1)-
(getGrayPoint(x-1,y-1)+2*getGrayPoint(x-1,y)+getGrayPoint(x-1,y+1));
int grayY = (getGrayPoint(x-1, y+1) + 2*getGrayPoint(x,y+1)+getGrayPoint(x+1,y+1))-
(getGrayPoint(x-1,y-1) + 2*getGrayPoint(x,y-1) + getGrayPoint(x+1,y-1));
gradient[x+y*mWidth] = (int) Math.sqrt(grayX*grayX+grayY*grayY);
}
}
方法gradient(x,y)
:
private int getGrayPoint(int x,int y){
return mGrayData[x+y*mWidth];
}
输入图片:
并且在完成之后:
现在我该如何实现呢?
我不知道如何使用渐变数据。我试试这个:
int[] gradient = getGradient();
int maxGradient = gradient[0];
for (int i=0;i<gradient.length;i++){
if (gradient[i]>maxGradient)
maxGradient = gradient[i];
}
float scaleFactor = 255.0f / maxGradient;
for (int y = 1; y < mHeight - 1; ++y)
for (int x = 1; x < mWidth - 1; ++x)
if (Math.round(scaleFactor * gradient[y * mWidth + x]) >= mThreshold)
{
mNewImage.setRGB(x, y, 0x000000);
}else {
mNewImage.setRGB(x,y,mGrayData[y * mWidth + x]);
}
File file = new File("D:\\Documents\\Pictures\\engine3.png");
if (!file.exists()) {
file.getParentFile().mkdir();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
ImageIO.write(mNewImage, "png", file);
} catch (IOException e) {
e.printStackTrace();
}
我得到了图片:
答案 0 :(得分:1)
您似乎使用错误的数据进行渐变计算。您的mGrayData
包含整数值0xAXXX,其中A
为alpha,X
为灰色值(按r,g,b的平均值计算)。
改为使用
mGrayData[i * mWidth + j] = average;
第二次修改:
建议:
private int getGrayPoint(int x,int y){
return mGrayData[x+y*mWidth] & 0xff;
}