我有一组气象 RGB 类型 BufferedImage
。我想得到他们的平均形象。也就是说,我的意思是获取每个像素的平均值并根据这些值制作新图像。我试过的是这样的:
public void getWaveImage(BufferedImage input1, BufferedImage input2){
// images are of same size that's why i'll use first one's width and height
int width = input1.getWidth(), height = input1.getHeight();
BufferedImage output = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
int[] rgb1 = input1.getRGB(0, 0, width, height, new int[width * height], 0, width);
int[] rgb2 = input2.getRGB(0, 0, width, height, new int[width * height], 0, width);
for(int i=0; i<width; i++){
for(int j=0; j<height; j++){
int rgbIndex = i * width + j;
rgb1[rgbIndex] = (rgb1[rgbIndex] + rgb2[rgbIndex]) / 2;
}
}
output.setRGB(0, 0, width, height, rgb1, 0, width);
return output;
}
我做错了什么?提前谢谢你。
输入1:
输入2:
输出:
最佳答案
您需要颜色的每个分量的平均值,平均红色、平均绿色、平均蓝色。
相反,您是对整个整数取平均值。
Color c1 = new Color(rgb1[rgbIndex]);
Color c2 = new Color(rgb2[rgbIndex]);
Color cA = new Color((c1.getRed() + c2.getRed())/2,
(c1.getGreen() + c2.getGreen())/2,
(c1.getBlue() + c2.getBlue())/2);
rgb1[rgbIndex] = cA.getRGB();
由于创建了这么多对象,这可能不是最有效的,所以更直接的方法是这样的:
public static int average(int argb1, int argb2){
return (((argb1 & 0xFF) + (argb2 & 0xFF)) >> 1) | //b
(((argb1 >> 8 & 0xFF) + (argb2 >> 8 & 0xFF)) >> 1) << 8 | //g
(((argb1 >> 16 & 0xFF) + (argb2 >> 16 & 0xFF)) >> 1) << 16 | //r
(((argb1 >> 24 & 0xFF) + (argb2 >> 24 & 0xFF)) >> 1) << 24; //a
}
用法:
rgb1[rgbIndex] = average(rgb1[rgbIndex], rgb2[rgbIndex]);
关于java - 在java中获取一组图像的平均图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39851404/