gpt4 book ai didi

java - 突出显示图像之间的差异

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:59:42 25 4
gpt4 key购买 nike

我应该修改此图像比较代码以突出显示/指出两个图像之间的差异。有没有办法修改此代码以突出显示图像中的差异。如果没有关于如何进行的任何建议,我们将不胜感激。

 int width1 = img1.getWidth(null);
int width2 = img2.getWidth(null);
int height1 = img1.getHeight(null);
int height2 = img2.getHeight(null);
if ((width1 != width2) || (height1 != height2)) {
System.err.println("Error: Images dimensions mismatch");
System.exit(1);
}
long diff = 0;
for (int i = 0; i < height1; i++) {
for (int j = 0; j < width1; j++) {
int rgb1 = img1.getRGB(j, i);
int rgb2 = img2.getRGB(j, i);
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = (rgb1) & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = (rgb2) & 0xff;
diff += Math.abs(r1 - r2);
diff += Math.abs(g1 - g2);
diff += Math.abs(b1 - b2);
}
}
double n = width1 * height1 * 3;
double p = diff / n / 255.0;
return (p * 100.0);

最佳答案

这个解决方案对我有用。它突出了差异,并且在我尝试过的方法中具有最佳性能。 (假设:图像大小相同。此方法尚未使用透明胶片进行测试。)

比较 1600x860 PNG 图像 50 次的平均时间(在同一台机器上):

  • JDK7 ~178 毫秒
  • JDK8 ~139 毫秒

有没有人有更好/更快的解决方案?

public static BufferedImage getDifferenceImage(BufferedImage img1, BufferedImage img2) {
// convert images to pixel arrays...
final int w = img1.getWidth(),
h = img1.getHeight(),
highlight = Color.MAGENTA.getRGB();
final int[] p1 = img1.getRGB(0, 0, w, h, null, 0, w);
final int[] p2 = img2.getRGB(0, 0, w, h, null, 0, w);
// compare img1 to img2, pixel by pixel. If different, highlight img1's pixel...
for (int i = 0; i < p1.length; i++) {
if (p1[i] != p2[i]) {
p1[i] = highlight;
}
}
// save img1's pixels to a new BufferedImage, and return it...
// (May require TYPE_INT_ARGB)
final BufferedImage out = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
out.setRGB(0, 0, w, h, p1, 0, w);
return out;
}

用法:

import javax.imageio.ImageIO;
import java.io.File;

ImageIO.write(
getDifferenceImage(
ImageIO.read(new File("a.png")),
ImageIO.read(new File("b.png"))),
"png",
new File("output.png"));

Some inspiration...

关于java - 突出显示图像之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25022578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com