Java提取图片边缘
package qrcodeServer;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ServerMain {
static final String rootpath="E:\\desktop\\";
static final int Y=30;
static boolean isboard(BufferedImage ash,int now_x,int now_y,int w,int h,int[][] kernel1,int[][] kernel2)
{
int tmp=kernel1.length/2;
int x=now_x-tmp,y=now_y-tmp;
int ken1=0,ken2=0;
for(int i=x;i<x+kernel1.length;i++)
{
for(int j=y;j<y+kernel1.length;j++)
{
if(i<0||j<0||i>=w||j>=h)
{
return true;
}
ken1+=RGBtoAsh(ash.getRGB(i, j))*kernel1[i-x][j-y];
ken2+=RGBtoAsh(ash.getRGB(i, j))*kernel2[i-x][j-y];
}
}
ken1=ken1<0?-ken1:ken1;
ken2=ken2<0?-ken2:ken2;
return (ken1+ken2)/2>Y;
}
public static int RGBtoAsh(int rgb)
{
int tmp=0;
for(int i=0;i<3;i++)
{
tmp+=(rgb>>(i*8))&0xFF;
}
return tmp/3;
}
public static int AshtoRGB(int ash)
{
int tmp=0xFF000000;
for(int i=0;i<3;i++)
{
tmp|=(ash<<(i*8));
}
return tmp;
}
public static void main(String[] args) {
try {
BufferedImage bimg=ImageIO.read(new File(rootpath+"1.jpg"));
int w=bimg.getWidth(),h=bimg.getHeight();
BufferedImage bimgot=new BufferedImage(w, h, Image.SCALE_DEFAULT);
BufferedImage tmp=new BufferedImage(w, h, Image.SCALE_DEFAULT);
int kernel1[][]= {{1,1,1,1},
{0,0,0,0},
{0,0,0,0},
{-1,-1,-1,-1}};
int kernel2[][]= {{-1,0,0,1},
{-1,0,0,1},
{-1,0,0,1},
{-1,0,0,1}
};
for(int i=0;i<bimg.getWidth();i++)
for(int j=0;j<bimg.getHeight();j++)
{
if(isboard(bimg, i, j, w, h, kernel1,kernel2))
bimgot.setRGB(i,j,0);
else
bimgot.setRGB(i,j,0xFFFFFFFF);
}
ImageIO.write(bimgot, "jpg",new File(rootpath+"out.jpg"));
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
下面是效果演示