如何使用Node.js比较两张图片

33

我正在寻找一种比较两张图片相似度的方法。通过谷歌搜索得到了大量的图像处理结果(裁剪,重新调整大小等),但没有任何可以进行近似图像比较的东西。有一个 Node.js 库,但它是 0.0.1 版本,并且依赖于各种第三方系统包,因此不稳定或可移植。

需要类似下列的东西:

var imgComparator = require('some-awesome-image-comparator-module');
// result would be between 1.0 and 0.0, where 1.0 would mean exact match
var result = imgComparator.compare('/path/to/image/1.png', '/path/to/image/2.png');
4个回答

16

13

还有image-diff也很有前途,由Uber开发。

var imageDiff = require('image-diff')

imageDiff({
  actualImage: 'checkerboard.png',
  expectedImage: 'white.png'
}, function (err, imagesAreSame) {
  // error will be any errors that occurred
  // imagesAreSame is a boolean whether the images were the same or not
  // diffImage will have an image which highlights differences
})

3
需要这些图像完全相同吗?我想要比较两幅图像是否相似。例如:同一座建筑物的相同照片,但因不是同一张照片而略有不同。 - chovy
就此而言,image-diff是一个薄的包装器,围绕imagemagick/graphicsmagick的compare工具构建。 - mrm
8
弃用,建议使用looks-samepixelmatch - krulik

8

image-diff已经停止维护。

来自他们的github:

我们项目中没有活跃的维护者,因此停止了维护。

作为替代方案,请参考类似looks-same和pixelmatch等备选项目:

https://github.com/gemini-testing/looks-same

https://github.com/mapbox/pixelmatch

个人推荐使用pixelmatch:

最小、最简单和最快速的JavaScript像素级图像比较库,最初用于测试中比较屏幕截图。

具有准确的反锯齿像素检测和感知色差度量功能。

受Resemble.js和Blink-diff启发。与这些库不同的是,pixelmatch仅有大约150行代码,没有任何依赖项,并且可以在原始类型化的图像数据上工作,因此非常快速,并且可以在任何环境(Node或浏览器)中使用。

const fs = require('fs');
const PNG = require('pngjs').PNG;
const pixelmatch = require('pixelmatch');

const img1 = PNG.sync.read(fs.readFileSync('img1.png'));
const img2 = PNG.sync.read(fs.readFileSync('img2.png'));
const {width, height} = img1;
const diff = new PNG({width, height});

const difference = pixelmatch(img1.data, img2.data, diff.data, width, height, {threshold: 0.1});

fs.writeFileSync('diff.png', PNG.sync.write(diff)); // see diff.png for the difference

const compatibility = 100 - dif * 100 / (width * height);
console.log(`${difference} pixels differents`);
console.log(`Compatibility: ${compatibility}%`);

在这里查看演示:https://observablehq.com/@mourner/pixelmatch-demo https://github.com/mapbox/pixelmatch

但是像素匹配仅适用于PNG格式,我和作者遇到了类似的问题,我需要使用nodeJS比较2个jpg图像,而像素匹配对此无效... - Gintars Lazda
你可以使用sharp将不同格式的文件转换为PNG/PNG缓冲区。 - marsnebulasoup

3

请保持更新,因为我还没有让它工作 :). - Dan
在“bin/imagediff”中有一个如何使用该库的示例。将Canvas模块的存储版本命名为imagediff,最新版本似乎不兼容。阅读Canvas和Cairo的安装手册。我曾经卡了很长时间,因为错过了需要将文件夹添加到我的PATH的步骤。 - luff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接