您的位置:首页 > 编程语言 > Java开发

java 加载图像,显示图像和图像的灰度化

2014-07-27 00:23 393 查看
阅读前请看<前言>,谢谢!

用java基础包中,提供了图像的类,我们常用到的有java.awt.image.BufferedImage,javax.imageio.ImageIO等等,事实上这两个类就够了。前一个有关图像的基本操作,后一个为读取图像。

加载图像:

                BufferedImage img = null;
		try{
			img = ImageIO.read(new FileInputStream("/home/eple/DIP/o.jpg"));
		
		}catch (IOException e) {
			//e.printStackTrace();
		}


我是在ubuntu下运行的,所以文件路径和windows的略微不同。

为了使代码更通用,我自己新建了一个图像处理的类Imgae。

public class Image{
	
	public int h; //高
	public int w; //宽
	public int[] data; //像素
	public boolean gray; //是否为灰度图像
	
	public Image(BufferedImage img){
		
		this.h = img.getHeight();
		this.w = img.getWidth();
		
		this.data = img.getRGB(0, 0, w, h, null, 0, w);
		this.gray = false;
		toGray(); //灰度化
	}
	
	public Image(BufferedImage img,int gray){
		
		this.h = img.getHeight();
		this.w = img.getWidth();
		this.data = img.getRGB(0, 0, w, h, null, 0, w);
		this.gray = false;

	}

	public Image(int[] data,int h,int w){
		this.data = (data == null) ? new int[w*h]:data;
		this.h = h;
		this.w = w;
		this.gray = false;
	}
	
	public Image(int h,int w){
		this(null,h,w);
	}

        public BufferedImage toImage(){
               BufferedImage image = new BufferedImage(this.w, this.h, BufferedImage.TYPE_INT_ARGB);
               int[] d= new int[w*h];
               for(int i=0;i<this.h;i++){
               for(int j=0;j<this.w;j++){
                   if(this.gray){
                       d[j+i*this.w] = (255<<24)|(data[j+i*this.w]<<16)|(data[j+i*this.w]<<8)|(data[j+i*this.w]);
                   }else{
                       d[j+i*this.w] = data[j+i*this.w];
                   }
               }
         }
            image.setRGB( 0, 0, w, h, d, 0, w ); 
            return image;
     }

}


这样可以不依赖java自身提供的方法,我们只需要把图像转成我们所定义的类即可。比如在android中,像素的读取和生存如下,只要将相关函数替换即可。

 //android 中的获取方式RGB分量  
   pixelsA = Color.alpha(color);  
   pixelsR = Color.red(color);  
   pixelsG = Color.green(color);  
   pixelsB = Color.blue(color);
	                
 // 根据新的RGB生成新像素  
   newPixels[i] = Color.argb(pixelsA, pixelsR, pixelsG, pixelsB);


好了,上面的类就包含了读取图像像素信息保存为int数组和将int数组重新转化为Bufferedmage的方法。下面我们就讲讲如何对图像去色,即灰度化。

上一篇我们说到过,对图像处理的事实,我们更关心图像的亮度信息,也就是灰度,如何将彩色图像转换成灰度图像呢?很简单,只要令R,G,B三个值相等即可。那么这个值和原R,G,B的值是什么关系呢?

一般的,我们有经验公式 Gray=R×0.299+G×0.587+B×0.114,或者直接取它们的均值即可。前面的经验公式更符合人眼的观测。灰度化函数如下:

public void toGray(){
		
		if(!gray){
			this.gray = true;
			for (int y = 0; y < h; y++) {
	                   for (int x = 0; x < w; x++) {
	                      int c = this.data[x + y * w];
	                      int R = (c >> 16) & 0xFF;
	                      int G = (c >> 8) & 0xFF;
	                      int B = (c >> 0) & 0xFF;
	                      this.data[x + y * w] = (int)(0.3f*R + 0.59f*G + 0.11f*B); //to gray
	            }
	          }
		}
	}


处理效果如下:





以上
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: