我正在使用洪水填充算法对图像进行排序。如果它遇到相同的颜色,我希望它将该像素复制到一个相同大小的数组中,称为填充。然后将填充的数组转换回图像并保存为 jpg。但是,当我打开 jpg 时,它看起来完全是黑色的。
public static void findFace(int[][] image) throws IOException {
int height = image.length;
int width = image[0].length;
Color centerStart = new Color(image[width / 2][height / 2]);
int[][] filled = new int[width][height];
floodFill(width / 2, height / 2, centerStart, image, filled);
//construct the filled array as image. Show if the face was found.
BufferedImage bufferImage2 = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int Pixel = filled[x][y] << 16 | filled[x][y] << 8 | filled[x][y];
bufferImage2.setRGB(x, y, Pixel);
}
}
//save filled array as image file
File outputfile = new File("/home/lily/Pictures/APicaDay/saved.jpg");
ImageIO.write(bufferImage2, "jpg", outputfile);
}
public static int[][] floodFill(int x, int y, Color targetColor, int[][] image, int[][] filled) {
if (image[x][y] != targetColor.getRGB()) {
return filled;
}
filled[x][y] = image[x][y];
floodFill(x - 1, y, targetColor, image, filled);
floodFill(x + 1, y, targetColor, image, filled);
floodFill(x, y - 1, targetColor, image, filled);
floodFill(x, y + 1, targetColor, image, filled);
return filled;
}
额外问题:我希望洪水填充也接受相似但不完全相同的颜色,因为我正在处理照片。