2

我是 node js 的初学者,所以我正在寻找一种方法来使用 jimp 为我的项目比较两个图像。我想知道这是否可能,是否有可能执行此操作的代码和方法,或者是否有其他方法可以做到这一点。

4

1 回答 1

1

这是比较图像的示例,我们可以使用像素距离或汉明距离进行比较。

这与 Jimp 文档中的示例非常相似,尽管我们是从在线资源加载图像。

您可以使用阈值,我们在这里使用与 Jimp 在其演示中使用的相同。

const Jimp = require('jimp');

async function compareImages(image1Url, image2Url) {

    const image1 = await Jimp.read(image1Url);
    const image2 = await Jimp.read(image2Url);
    // Perceived distance
    const distance = Jimp.distance(image1, image2);
    // Pixel difference
    const diff = Jimp.diff(image1, image2);
    
    console.log(`compareImages: distance: ${distance.toFixed(3)}, diff.percent: ${diff.percent.toFixed(3)}`);
    if (distance < 0.15 || diff.percent < 0.15) {
        console.log("compareImages: Images match!");
        return true;
    } else {
        console.log("compareImages: Images do NOT match!");
        return false;
    }
}

const usFlag = "https://flaglane.com/download/american-flag/american-flag-small.jpg";
const canadianFlagJpg = "https://flaglane.com/download/canadian-flag/canadian-flag-small.jpg";
const canadianFlagPng = "https://flaglane.com/download/canadian-flag/canadian-flag-small.png";

// These should not match.
compareImages(usFlag, canadianFlagJpg);

// These should match.
compareImages(canadianFlagJpg, canadianFlagPng);
于 2020-07-02T12:15:12.700 回答