我的老师给了我们一个任务,让我们制作一个640x480 bmp彩色图像的课程,把它转换成灰度图像,我找到了一些有想法的来源,所以我就做了。但有一个问题,因为它似乎使它,因为它没有给我错误,但输出没有出现。我想这是我的密码。我的代码是
import java.io.*;
public class Grayscale{
FileInputStream image;
FileOutputStream img;
byte[] datos;
int gray;
public Grayscale(String nombre)throws Exception{
this.image = new FileInputStream(nombre);
this.img = img;
this.datos = new byte[image.available()];
this.gray = gray;
}
public void gray()throws Exception{
image.read(datos);
img = new FileOutputStream("grayscaleprueba.bmp");
for (int i = 0; i<datos.length; i++){
gray = (byte)(datos[i]*0.3 + datos[i+1]*0.59 + datos[i+2]);
datos[i] = (byte)gray;
datos[i+1] = (byte)gray;
datos[i+2] = (byte)gray;
}
img.write(datos);
}
}发布于 2013-09-11 14:48:52
除了@joni提到的那些问题之外,还有一些问题。这个问题比最初看上去的要深一点。
BMP文件格式
循环播放
处理每个像素的3个字节,然后以1的增量遍历文件。通过3D眼镜观看得到的图像可能非常有趣,但也意味着出现了一些奇怪的图像。
for (int i = 0; i<datos.length; i+=3){ // increment by 3 instead of 1
gray = (byte)(datos[i]*0.3 + datos[i+1]*0.59 + datos[i+2]);
datos[i] = (byte)gray;
datos[i+1] = (byte)gray;
datos[i+2] = (byte)gray;
}有符号字节
对Java中的字节进行签名。它从-128到127,所以你的算术无效。对于每一个字节,我都会使用它作为int,并在用权重将它们相加之前添加128。然后,在求和后,减去128,然后转换为字节。
像素变换值范围
您可以将saem范围中的3个数字相加,并希望在范围本身中得到一个数字。但是,您的权重不反映这一点:权重应该加起来为1。首先,对于所有的值,我都使用0.33 (这不能给出完美的颜色权重,但在技术上应该有效)。
//using double to have some precision
double temp = datos[i]/3.0d + datos[i+1]/3.0d + datos[i]/3.0d;
gray = (byte)(Math.round(temp)-128); //rounding to Long, and converting to byt value range发布于 2013-09-11 14:41:05
这个代码有几个问题:
available方法只告诉您立即可用的字节数,而不必实际从磁盘读取。它很可能返回0。read方法只读取数据的一部分。返回值告诉您实际读取的字节数。发布于 2013-09-11 14:50:55
在您的代码中有很多东西不能工作。
https://stackoverflow.com/questions/18744123
复制相似问题