用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免费学习笔记(深入)”;
本文档主要讲述的是基于VC与Matlab的混合编程实现图像的三维显示;介绍了VC++与Matlab混合编程的一般实现方法,并实现对二维影像图的三维效果显示。 MATLAB既是一种直观、高效的计算机语言,同时又是一个科学计算平台。它为数据分析和数据可视化、算法和应用程序开发提供了最核心的数学和高级图形工具。希望本文档会给有需要的朋友带来帮助;感兴趣的朋友可以过来看看
9


以上就是java 加载图像,显示图像和图像的灰度化的内容,更多相关内容请关注PHP中文网(www.php.cn)!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号