利用java实现图像灰度化

24位色彩图

24位色彩图:每个像素通常使用四个字节存储,第一个字节为Alpha值,后三个字节为RGB。当R=G=B时,则色彩表示一种灰度颜色,其中R=G=B的值叫灰度值,范围0~255

 

几种灰度化的方法

分量法:使用RGB三个分量中的一个作为灰度图像的灰度值

最值法:使用RGB三个分量中最大值或最小值作为灰度图像的灰度值

均值法:使用RGB三个分量的平均值作为灰度图像的灰度值

加权法:灰度值Y=0.3*R+0.59*G+0.11*B

 

/*
     * 使用加权法把24位色彩图转化为灰度图
     */
	public static BufferedImage convertToGray(String imagePath)
	{
		BufferedImage bufferedImage = null;
		try
		{
			bufferedImage = ImageIO.read(new File(imagePath));
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	
		int width = bufferedImage.getWidth();
		int height = bufferedImage.getHeight();
		BufferedImage result = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
	
		for(int j = 0;j < height;j++)
		{
			for(int i = 0;i < width;i++)
			{
				int argb = bufferedImage.getRGB(i, j);
				int a =  argb >> 24 & 0xFF;
				int r = argb >> 16 & 0xFF;
				int g = argb >> 8 & 0xFF;
				int b = argb & 0xFF;
			
				int gray = (int)(0.3 * r + 0.59 * g + 0.11 * b); //灰度值
				int grayARGB = a << 24 | gray << 16 | gray << 8  | gray; 
			
				result.setRGB(i, j, grayARGB);	
			}
		}
		return result;
	}

 

若设置为BufferedImage.TYPE_INT_RGB,则不用考虑Alpha值

	/*
	 * 使用加权法把24位色彩图转化为灰度图
	 */
	public static BufferedImage convertToGray(String imagePath)
	{
		BufferedImage bufferedImage = null;
		try
		{
			bufferedImage = ImageIO.read(new File(imagePath));
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		int width = bufferedImage.getWidth();
		int height = bufferedImage.getHeight();
		BufferedImage result = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		
		for(int j = 0;j < height;j++)
		{
			for(int i = 0;i < width;i++)
			{
				int rgb = bufferedImage.getRGB(i, j);
				int r = rgb >> 16 & 0xFF;
				int g = rgb >> 8 & 0xFF;
				int b = rgb & 0xFF;
				
				int gray = (int)(0.3 * r + 0.59 * g + 0.11 * b); //灰度值
				int grayRGB = 255 << 24 | gray << 16 | gray << 8  | gray; 
				
				result.setRGB(i, j, grayRGB);	
			}
		}
		return result;
	}

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值