我正在学习图像处理技术并做一些功课。 在我的作业中,要求我将RBG覆盖为灰色图像。 我已经将图像转换为2D矩阵,做了一些事情,当我再次从2D矩阵覆盖到图像时,会出现一些错误。 这是我的代码:
private static SampleModel samM;
public static int[][] imageToArrayPixel(File file) {
try {
BufferedImage img = ImageIO.read(file);
Raster raster = img.getData();
int w = raster.getWidth(), h = raster.getHeight();
int pixels[][] = new int[w][h];
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
pixels[x][y] = raster.getSample(x, y, 0);
System.out.print(" " + pixels[x][y]);
}
System.out.println("");
}
samM = raster.getSampleModel();
return pixels;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static java.awt.Image getImage(int pixels[][]) {
int w = pixels.length;
int h = pixels[0].length;
WritableRaster raster = Raster.createWritableRaster(samM, new Point(0, 0));
for (int i = 0; i < w; i++) {
for (int j = 0; j < pixels[i].length; j++) {
if (pixels[i][j] > 128) {
raster.setSample(i, j, 1, 255);
} else {
raster.setSample(i, j, 1, 0);
}
}
}
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
image.setData(raster);
File output = new File("check.jpg");
try {
ImageIO.write(image, "jpg", output);
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
public static java.awt.Image getImageWithRBG(Pixel pixels[][]) {
int w = pixels.length;
int h = pixels[0].length;
WritableRaster raster = Raster.createWritableRaster(samM, new Point(0, 0));
int[] pixelValue = new int[3];
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
pixelValue[0] = pixels[i][j].red;
pixelValue[1] = pixels[i][j].blue;
pixelValue[2] = pixels[i][j].green;
raster.setPixel(j, i, pixelValue);
}
}
BufferedImage image = new BufferedImage(h, w, BufferedImage.TYPE_CUSTOM);
image.setData(raster);
File output = new File("check.jpg");
try {
ImageIO.write(image, "jpg", output);
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
public static void main(String[] args) throws IOException {
int pixel[][] = imageToArrayPixel(new File("C:\\Users\\KimEricko\\Pictures\\1402373904964_500.jpg"));
getImage(pixel);
}
这是我用来隐蔽的形象: before 这是我在修复后收到的照片: after
我不明白为什么恢复后的照片仅包含原始照片的1/3。 我该怎么做才能解决这个问题?
答案 0 :(得分:0)
在我看来,getImageWithRBG中存在一个错误 raster.setPixel(j,i,pixelValue); 应该 raster.setPixel(i,j,pixelValue);
setPixel和setSample有类似的输入:x然后y
我不知道是否还有其他问题,这是我注意到的第一件事。