Java提取图片边缘

9 篇文章 0 订阅

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

下面是效果演示
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值