我用 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;
}
但它不起作用。我应该怎么做才能将该缓冲图像转换为相同图像数据的字节数组?