【发布时间】:2013-09-01 10:36:49
【问题描述】:
我用 Java 编写了一个用于图像处理的应用程序。我已经处理了作为缓冲图像的图像,现在我想为处理后的图像返回byte[],我应该得到二值化图像的字节数组。
这是我的代码:
public static byte[][] binarizeImage(BufferedImage bfImage){
int red;
int newPixel;
int h ;
int w ;
int threshold = otsuTreshold(bfImage);
// this function returns the threshold value 199
BufferedImage binarized = new BufferedImage(bfImage.getWidth(), bfImage.getHeight(), bfImage.getType());
for(int i=0; i<bfImage.getWidth(); i++) {
for(int j=0; j<bfImage.getHeight(); j++) {
// Get pixels
red = new Color(bfImage.getRGB(i, j)).getRed();
int alpha = new Color(bfImage.getRGB(i, j)).getAlpha();
if(red > threshold) {
newPixel = 255;
}
else {
newPixel = 0;
}
newPixel = colorToRGB(alpha, newPixel, newPixel, newPixel);
binarized.setRGB(i, j, newPixel);
}
}
Raster raster = binarized.getData();
h = raster.getHeight();
w = raster.getWidth();
byte[][] binarize_image = new byte[w][h];
for(int i=0 ; i<w ; i++)
{
for(int j=0; j<h ; j++)
{
binarize_image[i][j]=raster.getSampleModel(); //error at this line
}
}
return binarize_image;
}
// Convert R, G, B, Alpha to standard 8 bit
private static int colorToRGB(int alpha, int red, int green, int blue) {
int newPixel = 0;
newPixel += alpha;
newPixel = newPixel << 8;
newPixel += red; newPixel = newPixel << 8;
newPixel += green; newPixel = newPixel << 8;
newPixel += blue;
return newPixel;
}
但它不起作用。我应该怎么做才能将该缓冲图像转换为相同图像数据的字节数组?
【问题讨论】:
-
转换后您希望
binarize_image包含什么内容?每像素 8 位黑/白 + 8 位 alpha?如果是这样,您希望如何将其存储为每像素 8 位?这并不是我所认为的二进制,但你可能正在创造一种艺术效果?在任何情况下,您都可以不使用临时的binarized图像,只需在第一个循环中直接将值设置为binarize_image。 -
编写代码的主要目的是只想将灰度图像转换为二值化图像。我正在尝试使用上面的代码。
-
什么是“二值化”图像?你的意思是二进制,只有黑/白?你的输入图像总是灰色的吗? 8 位?
-
是二值化图像是指黑白图像
标签: java image image-processing bytearray bufferedimage