您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2024/11/11 19:58:58发布18次查看
用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 } } } }
处理效果如下:
以上就是java 加载图像,显示图像和图像的灰度化的内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product