Code Monkey home page Code Monkey logo

blink-diff's Introduction

Blink-Diff

A lightweight image comparison tool

Build Status Coveralls Coverage Code Climate Grade

NPM version NPM License

NPM NPM

Coverage Report API Documentation

Gitter Support

Table of Contents

##Image Comparison and Result Composition

##Installation

Install this module with the following command:

npm install blink-diff

Add the module to your package.json dependencies:

npm install --save blink-diff

Add the module to your package.json dev-dependencies:

npm install --save-dev blink-diff

##Usage

The package can be used in two different ways:

  • per command line
  • through an object

###Command-Line usage

The command-line tool can be found in the bin directory. You can run the application with

blink-diff --output <output>.png <image1>.png <image2>.png

Use image1 and image2 as the images you want to compare. Only PNGs are supported at this point.

The command-line tool exposes a couple of flags and parameters for the comparison:

--verbose           Turn on verbose mode
--debug             Turn on debug mode - leaving all filters and modifications on the result
--threshold p       Number of pixels/percent 'p' below which differences are ignored
--threshold-type t  'pixel' and 'percent' as type of threshold. (default: pixel)
--delta p           Max. distance colors in the 4 dimensional color-space without triggering a difference. (default: 20)
--copyImageA        Copies first image to output as base. (default: true)
--copyImageB        Copies second image to output as base.
--no-copy           Doesn't copy anything to output as base.
--output o          Write difference to the file 'o'
--filter f          Filters f (separated with comma) that will be applied before the comparison.
--no-composition    Turns the composition feature off
--compose-ltr       Compose output image from left to right
--compose-ttb       Compose output image from top to bottom
--hide-shift        Hides shift highlighting (default: false)
--h-shift           Acceptable horizontal shift of pixel. (default: 0)
--v-shift           Acceptable vertical shift of pixel. (default: 0)
--block-out x,y,w,h Block-out area. Can be repeated multiple times.
--version           Print version
--help              This help

###Object usage

The package can also be used directly in code, without going through the command-line.

Example:

var diff = new BlinkDiff({
    imageAPath: 'path/to/first/image', // Use file-path
    imageBPath: 'path/to/second/image',

    thresholdType: BlinkDiff.THRESHOLD_PERCENT,
    threshold: 0.01, // 1% threshold

    imageOutputPath: 'path/to/output/image'
});

diff.run(function (error, result) {
   if (error) {
      throw error;
   } else {
      console.log(diff.hasPassed(result.code) ? 'Passed' : 'Failed');
      console.log('Found ' + result.differences + ' differences.');
   }
});

All the parameters that were available in the command-line tool are also available through the class constructor, however they might use slightly different wording. The class exposes additional parameters that are not available from the command-line:

  • imageAPath Defines the path to the first image that should be compared (required; imageAPath or imageA is required - see example below)
  • imageA Supplies first image that should be compared (required; imageAPath or imageA is required - see example below) - This can be a PNGImage instance or a Buffer instance with PNG data
  • imageBPath Defines the path to the second image that should be compared (required; imageBPath or imageB is required - see example below)
  • imageB Supplies second image that should be compared (required; imageBPath or imageB is required - see example below) - This can be a PNGImage instance or a Buffer instance with PNG data
  • imageOutputPath Defines the path to the output-file. If you leaves this one off, then this feature is turned-off.
  • imageOutputLimit Defines when an image output should be created. This can be for different images, similar or different images, or all comparisons. (default: BlinkDiff.OUTPUT_ALL)
  • verbose Verbose output (default: false)
  • thresholdType Type of threshold check. This can be BlinkDiff.THRESHOLD_PIXEL and BlinkDiff.THRESHOLD_PERCENT (default: BlinkDiff.THRESHOLD_PIXEL)
  • threshold Number of pixels/percent p below which differences are ignored (default: 500) - For percentage thresholds: 1 = 100%, 0.2 = 20%
  • delta Distance between the color coordinates in the 4 dimensional color-space that will not trigger a difference. (default: 20)
  • outputMaskRed Red intensity for the difference highlighting in the output file (default: 255)
  • outputMaskGreen Green intensity for the difference highlighting in the output file (default: 0)
  • outputMaskBlue Blue intensity for the difference highlighting in the output file (default: 0)
  • outputMaskAlpha Alpha intensity for the difference highlighting in the output file (default: 255)
  • outputMaskOpacity Opacity of the pixel for the difference highlighting in the output file (default: 0.7 - slightly transparent)
  • outputShiftRed Red intensity for the shift highlighting in the output file (default: 255)
  • outputShiftGreen Green intensity for the shift highlighting in the output file (default: 165)
  • outputShiftBlue Blue intensity for the shift highlighting in the output file (default: 0)
  • outputShiftAlpha Alpha intensity for the shift highlighting in the output file (default: 255)
  • outputShiftOpacity Opacity of the pixel for the shift highlighting in the output file (default: 0.7 - slightly transparent)
  • outputBackgroundRed Red intensity for the background in the output file (default: 0)
  • outputBackgroundGreen Green intensity for the background in the output file (default: 0)
  • outputBackgroundBlue Blue intensity for the background in the output file (default: 0)
  • outputBackgroundAlpha Alpha intensity for the background in the output file (default: undefined)
  • outputBackgroundOpacity Opacity of the pixel for the background in the output file (default: 0.6 - transparent)
  • blockOut Object or list of objects with coordinates that should be blocked before testing.
  • blockOutRed Red intensity for the block-out in the output file (default: 0) This color will only be visible in the result when debug-mode is turned on.
  • blockOutGreen Green intensity for the block-out in the output file (default: 0) This color will only be visible in the result when debug-mode is turned on.
  • blockOutBlue Blue intensity for the block-out in the output file (default: 0) This color will only be visible in the result when debug-mode is turned on.
  • blockOutAlpha Alpha intensity for the block-out in the output file (default: 255)
  • blockOutOpacity Opacity of the pixel for the block-out in the output file (default: 1.0)
  • copyImageAToOutput Copies the first image to the output image before the comparison begins. This will make sure that the output image will highlight the differences on the first image. (default)
  • copyImageBToOutput Copies the second image to the output image before the comparison begins. This will make sure that the output image will highlight the differences on the second image.
  • filter Filters that will be applied before the comparison. Available filters are: blur, grayScale, lightness, luma, luminosity, sepia
  • debug When set, then the applied filters will be shown on the output image. (default: false)
  • composition Creates as output a composition of all three images (approved, highlight, and build) (default: true)
  • composeLeftToRight Creates comparison-composition from left to right, otherwise it lets decide the app on what is best
  • composeTopToBottom Creates comparison-composition from top to bottom, otherwise it lets decide the app on what is best
  • hShift Horizontal shift for possible antialiasing (default: 2) Set to 0 to turn this off.
  • vShift Vertical shift for possible antialiasing (default: 2) Set to 0 to turn this off.
  • hideShift Uses the background color for "highlighting" shifts. (default: false)
  • cropImageA Cropping for first image (default: no cropping) - Format: { x:, y:, width:, height: }
  • cropImageB Cropping for second image (default: no cropping) - Format: { x:, y:, width:, height: }
  • perceptual Turn the perceptual comparison mode on. See below for more information.
  • gamma Gamma correction for all colors (will be used as base) (default: none) - Any value here will turn the perceptual comparison mode on
  • gammaR Gamma correction for red - Any value here will turn the perceptual comparison mode on
  • gammaG Gamma correction for green - Any value here will turn the perceptual comparison mode on
  • gammaB Gamma correction for blue - Any value here will turn the perceptual comparison mode on

Example:

var firstImage = PNGImage.readImage('path/to/first/image', function (err) {

  if (err) {
    throw err;
  }

  var diff = new BlinkDiff({
      imageA: srcImage, // Use already loaded image for first image
      imageBPath: 'path/to/second/image', // Use file-path to select image

      delta: 50, // Make comparison more tolerant
      
      outputMaskRed: 0,
      outputMaskBlue: 255, // Use blue for highlighting differences
      
      hideShift: true, // Hide anti-aliasing differences - will still determine but not showing it

      imageOutputPath: 'path/to/output/image'
  });

  diff.run(function (error, result) {
    if (error) {
      throw error;
    } else {
      console.log(diff.hasPassed(result.code) ? 'Passed' : 'Failed');
      console.log('Found ' + result.differences + ' differences.');
    }
  });
});

####Cropping Images can be cropped before they are compared by using the cropImageA or cropImageB parameters. Single values can be left off, and the system will calculate the correct dimensions. However, x/y coordinates have priority over width/height as the position are usually more important than the dimensions - image will also be clipped by the system when needed.

####Perceptual Comparison The perceptual comparison mode considers the perception of colors in the human brain. It transforms all the colors into a human perception color-space, which is quite different to the typical physical bound RGB color-space. There, in the perceptual color-space, the distance between colors is according to the human perception and should therefore closer resemble the differences a human would perceive seeing the images.

####Logging

By default, the logger doesn't log events anywhere, but you can change this behavior by overwriting blinkDiff.log:

var blinkDiff = new BlinkDiff({
    ...
});

blinkDiff.log = function (text) {
    // Do whatever you want to do
};

...

####Block-Out Sometimes, it is necessary to block-out some specific areas in an image that should be ignored for comparisons. For example, this can be IDs or even time-labels that change with the time. Adding block-outs to images may decrease false positives and therefore stabilizes these comparisons.

The color of the block-outs can be selected by the API parameters. However, the block-out areas will not be visible by default - they are hidden even though they are used. To make them visible, turn the debug-mode on.

##Examples

There are some examples in the examples folder, in which I used screenshots of YDN to check for visual regressions (and made some manual modifications to the dom to make differences appear ;-)). You can find examples for:

  • Color changes in YDN_Color
  • Missing DOM elements in YDN_Missing (including some anti-aliasing)
  • Multiple differences in YDN_Multi
  • Disrupted sorting in YDN_Sort
  • Swapped items in YDN_Swap (including block-out areas)
  • Text capitalization in YDN_Upper

All screenshots were compared to YDN.png, a previously approved screenshot without a regression. Each of the regressions has the screenshot and the output result, highlighting the differences.

##API-Documentation

Generate the documentation with following command:

npm run docs

The documentation will be generated in the docs folder of the module root.

##Tests

Run the tests with the following command:

npm run test

The code-coverage will be written to the coverage folder in the module root.

##Project Focus There are three types of image comparisons:

  • Pixel-by-pixel - Used to compare low-frequency images like screenshots from web-sites, making sure that small styling differences trigger
  • Perceptual - Used to compare image creation applications, for example rendering engines and photo manipulation applications that are taking the human perception into account, ignoring differences a human probably would not see
  • Context - Used to see if parts of images are missing or are severely distorted, but accepts smaller and/or perceptual differences

Blink-Diff was initially created to compare screenshots. These images are generally low-frequency, meaning larger areas with the same color and less gradients than in photos. The pixel-by-pixel comparison was chosen as it will trigger for differences that a human might not be able to see. We believe that a bug is still a bug even if a human won't see it - a regression might have happened that wasn't intended. A perceptual comparison would not trigger small differences, possibly missing problems that could get worse down the road. Pixel-by-pixel comparisons have the reputation of triggering too often, adding manual labor, checking images by hand. Blink-Diff was created to keep this in mind and was optimized to reduce false-positives by taking sub-pixeling and anti-aliasing into account. Additional features like thresholds and the pythagorean distance calculation in the four dimensional color-space makes sure that this won't happen too often. Additionally, filters can be applied to the images, for example to compare luminosity of pixels and not the saturation thereof. Blink-Diff also supports partially the perceptual comparison that can be turned on when supplying perceptual=true. Then, the colors will be compared in accordance with the human perception and not according to the physical world. High-frequency filters, however, are not yet supported.

##Project Naming The name comes from the Blink comparator that was used in Astronomy to recognize differences in multiple photos, taking a picture of the same area in the sky over consecutive days, months, or years. Most notably, it was used to discover Pluto.

##Contributions Feel free to create an issue or create a pull-request if you have an idea on how to improve blink-diff. We are pretty relaxed on the contribution rules; add tests for your pull-requests when possible, but it is also ok if there are none - we'll add them for you. We are trying to improve blink-diff as much as possible, and this can only be done by contributions from the community.

Also, even if you simply gave us an idea for a feature and did not actually write the code, we will still add you as the Contributor down below since it probably wouldn't be there without you. So, keep them coming!

##Contributors

##Third-party libraries

The following third-party libraries are used by this module:

###Dependencies

###Dev-Dependencies

##License

The MIT License

Copyright 2014-2015 Yahoo Inc.

blink-diff's People

Contributors

azu avatar marcelerz avatar paragbhattacharjee avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

blink-diff's Issues

Return image buffer instead writing to output

Hello there,

I am currently developing a tool that will automatically extract images from an HTML document as Buffers, compare them, and create a 'diff-document' containing the output images from a blink-diff comparison of images with equal index.

For performance reasons, it is not optimal for me to have blink-diff write .png-files, only for me to read them as Buffers again.

However, I am for a while now failing to find a way to return the Output-Image as a Buffer, or in any way get an output convertible to such.
Can you help me with that? That would be very much appreciated!

Kindest regards in advance,
Timm Kühnel

with the o2r-project
Institute for Geoinformation
WWU Muenster, Germany

typo in README.md

"compareLeftToRight" in README.md should be "composeLeftToRight".
As well as "compareTopToBottom".

Can't have a delta equal to zero

Hello,

I want to compare my images with a delta of zero. But if I put a zero value to delta it will be overridden here:
this._delta = options.delta || 20;

I saw that there is the same thing for threshold.
If I override the delta to zero manually in the source code, I have the diff image that I need.

I can make a PR to check if options.delta and options.thresholdare undefined.
But is there a legitimate reason that delta and threshold can't be equal to zero?

Thanks,

No Composition Still Composing

Running with: ./blink-diff --no-composition --output out.png ../examples/YDN_Multi.png ../examples/YDN_Swap.png

Still produces an image made of all three images (YDN_Multi, YDN_Swap, and the diff).

Was hoping to get only the diff in out.png

TypeError: this._loadImage is not a function

I get this error when trying to use the library, here is the code I run:

const BlinkDiff = require('blink-diff');
const path = require('path');
const {promisify} = require('util');
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');

chai.should();
chai.use(chaiAsPromised);

const config = require('../../src/config');

function comparer(refImage, testImage, diffPath) {
    const diff = new BlinkDiff({
        imageAPath: refImage, // Use file-path
        imageBPath: testImage,

        thresholdType: BlinkDiff.THRESHOLD_PERCENT,
        threshold: config.tolerance,

        imageOutputPath: diffPath
    });

    return promisify(diff.run)();
}

describe('BlinkDiff comparing module', () => {
    it('should detect visual difference', () => {
        const result = comparer(
            path.join(__dirname, '../image/ref.png'),
            path.join(__dirname, '../image/test.png'),
            path.join(__dirname, '../image/diff.png'),
        );
        result.should.eventually.have.property('mismatchPercentage');
        result.should.eventually.deep.equal({misMatchPercentage: 1});
        result.then(({mismatchPercentage}) => {
            mismatchPercentage.should.be.lessThan(config.tolerance);
        })
    });
});

The error output

"C:\Program Files\nodejs\node.exe" D:\code\new-test\node_modules\mocha\bin\_mocha --ui bdd --reporter "C:\Program Files\JetBrains\WebStorm 2017.2.4\plugins\NodeJS\js\mocha-intellij\lib\mochaIntellijReporter.js" D:\code\new-test\test\lib\blinkdiff-comparer.test.js --grep "BlinkDiff comparing module "
TypeError: this._loadImage is not a function
    at D:\code\new-test\node_modules\blink-diff\index.js:359:16
    at D:\code\new-test\node_modules\promise\lib\es6-extensions.js:18:19
    at flush (D:\code\new-test\node_modules\asap\asap.js:27:13)
    at _combinedTickCallback (internal/process/next_tick.js:132:7)
    at process._tickCallback (internal/process/next_tick.js:181:9)
(node:8644) UnhandledPromiseRejectionWarning: TypeError: this._loadImage is not a function
    at D:\code\new-test\node_modules\blink-diff\index.js:359:16
    at D:\code\new-test\node_modules\promise\lib\es6-extensions.js:18:19
    at flush (D:\code\new-test\node_modules\asap\asap.js:27:13)
    at _combinedTickCallback (internal/process/next_tick.js:132:7)
    at process._tickCallback (internal/process/next_tick.js:181:9)
(node:8644) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:8644) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:8644) UnhandledPromiseRejectionWarning: TypeError: this._loadImage is not a function
    at D:\code\new-test\node_modules\blink-diff\index.js:359:16
    at D:\code\new-test\node_modules\promise\lib\es6-extensions.js:18:19
    at flush (D:\code\new-test\node_modules\asap\asap.js:27:13)
    at _combinedTickCallback (internal/process/next_tick.js:132:7)
    at process._tickCallback (internal/process/next_tick.js:181:9)
(node:8644) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:8644) UnhandledPromiseRejectionWarning: TypeError: this._loadImage is not a function
    at D:\code\new-test\node_modules\blink-diff\index.js:359:16
    at D:\code\new-test\node_modules\promise\lib\es6-extensions.js:18:19
    at flush (D:\code\new-test\node_modules\asap\asap.js:27:13)
    at _combinedTickCallback (internal/process/next_tick.js:132:7)
    at process._tickCallback (internal/process/next_tick.js:181:9)
(node:8644) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)

Process finished with exit code 0

Get output result file

I think it is not possible to get the result comparison file as a blob or something else.
I would like to have this option, since I am making comparisons of several images, and I wanted to generate only one results png file, with all image comparisons.

Different results from command-line vs JS Object usage

During testing of blink-diff I have experienced different results from the command-line usage vs. the Javascript Object usage.

Images used for this test:

people.png
people

people2.png
people2

Command-line Usage

Command-line script:
./node_modules/blink-diff/bin/blink-diff --output blinkdiff-people.png people.png people2.png

Command-line result:

bash-3.2$ ./blinkcli.sh
Blink-Diff 1.0.7
Copyright (C) 2014 Yahoo! Inc.
Images are visibly different
16297 pixels are different
Wrote differences to blinkdiff-people.png
Time: 197ms
Differences: 16297 (6.52%)
FAIL

Output file: blinkdiff-people.png - (Works as expected)
blinkdiff-people

Javascript Object Usage

blink.js

#!/usr/bin/env node

BlinkDiff = require('blink-diff')

var diff = new BlinkDiff({
    imageAPath: 'people.png',
    imageBPath: 'people2.png',

    imageOutputPath: 'blink-diff-people.png',

    verbose: true
});


diff.run(function (error) {
    console.log(error ? 'Failed' + error : 'Passed');
});

Run the script:
bash-3.2$ node blink.js

Output results (NOT as expected)

bash-3.2$ node blink.js 
Passed

Summary

Why are the results different? The results from the command-line usage are as expected, while the JS Object usage says "Passed" when it should say "Fail" and produce the output image.

Support for writing image only when not passed

Would be great if blinkdiff supported writing the image to disk only when the result is different as the default behaviour is for all.

Something like:

function BlinkDiff (options) {
    this._imageOutputOnfailure = options.imageOutputOnfailure || false;
}
            // Need to write to the filesystem?
            if (this._imageOutputPath) {

                if (this._imageOutputOnfailure && this.hasPassed(result)) {
                    fn(undefined, result);
                } else {
                    this._imageOutput.writeImage(this._imageOutputPath, function (err) {
                        if (err) {
                            fn(err);
                        } else {
                            this.log("Wrote differences to " + this._imageOutputPath);
                            fn(undefined, result);
                        }
                    }.bind(this));
                }
            } else {
                fn(undefined, result);
            }

Invalid file signature

Output:

thomas@workstation:goldshelf$ node compare.js 
{ _imageA: undefined,
  _imageAPath: '/Users/thomas/Desktop/goldshelf/learn/input.jpg',
  _imageB: undefined,
  _imageBPath: '/Users/thomas/Desktop/goldshelf/learn/desired.jpg',
  _imageOutput: null,
  _imageOutputPath: '/Users/thomas/Desktop/goldshelf/output-diff/',
  _imageOutputLimit: 100,
  _thresholdType: 'percent',
  _threshold: 0.01,
  _delta: 20,
  _outputMaskRed: 255,
  _outputMaskGreen: 0,
  _outputMaskBlue: 0,
  _outputMaskAlpha: 255,
  _outputMaskOpacity: 0.7,
  _outputBackgroundRed: 0,
  _outputBackgroundGreen: 0,
  _outputBackgroundBlue: 0,
  _outputBackgroundAlpha: undefined,
  _outputBackgroundOpacity: 0.6,
  _outputShiftRed: 200,
  _outputShiftGreen: 100,
  _outputShiftBlue: 0,
  _outputShiftAlpha: 255,
  _outputShiftOpacity: 0.7,
  _blockOut: [],
  _blockOutRed: 0,
  _blockOutGreen: 0,
  _blockOutBlue: 0,
  _blockOutAlpha: 255,
  _blockOutOpacity: 1,
  _copyImageAToOutput: true,
  _copyImageBToOutput: false,
  _filter: [],
  _debug: false,
  _composition: true,
  _composeLeftToRight: false,
  _composeTopToBottom: false,
  _hShift: 2,
  _vShift: 2,
  _cropImageA: undefined,
  _cropImageB: undefined,
  _refWhite: { c1: 1, c2: 1, c3: 1, c4: 1 },
  _perceptual: false,
  _gamma: undefined,
  _gammaR: undefined,
  _gammaG: undefined,
  _gammaB: undefined }
Invalid file signature
Error: Invalid file signature
    at Parser._parseSignature (/Users/thomas/Desktop/goldshelf/node_modules/blink-diff/node_modules/pngjs-image/node_modules/pngjs/lib/parser.js:87:32)
    at ChunkStream._process (/Users/thomas/Desktop/goldshelf/node_modules/blink-diff/node_modules/pngjs-image/node_modules/pngjs/lib/chunkstream.js:186:23)
    at ChunkStream.write (/Users/thomas/Desktop/goldshelf/node_modules/blink-diff/node_modules/pngjs-image/node_modules/pngjs/lib/chunkstream.js:74:10)
    at PNG.write (/Users/thomas/Desktop/goldshelf/node_modules/blink-diff/node_modules/pngjs-image/node_modules/pngjs/lib/png.js:100:18)
    at ReadStream.ondata (_stream_readable.js:524:20)
    at emitOne (events.js:77:13)
    at ReadStream.emit (events.js:166:7)
    at readableAddChunk (_stream_readable.js:146:16)
    at ReadStream.Readable.push (_stream_readable.js:109:10)
    at onread (fs.js:1726:12)

Code:

var path = require("path")
var BlinkDiff = require("blink-diff")

var input = path.join(__dirname, "./learn/input.jpg")
var desired = path.join(__dirname, "./learn/desired.jpg")
var output = path.join(__dirname, "./output-diff/")

var diff = new BlinkDiff({
    imageAPath: input,
    imageBPath: desired,
    thresholdType: BlinkDiff.THRESHOLD_PERCENT,
    threshold: 0.01,
    imageOutputPath: output
});

console.log(diff)

diff.run(function (error, result) {
   if (error) {
      throw error;
   } else {
      console.log(diff.hasPassed(result.code) ? 'Passed' : 'Failed');
      console.log('Found ' + result.differences + ' differences.');
   }
});

blink-diff shows Differences as '0%' & returns 'FAIL' as result

I have been using blink-diff for image comparison of selenium captured screens . For some comparisons I have noticed that blink-diff gives result as 'FAIL' however when looking at percentage difference , it shows '0%' . Doesn't that seem strange .
Comparisons having '0%' differences should be marked as 'PASS' , however blink-diff returns 'FAIL' ...

Below is the command line I use for doing screen comparison .

D:\>node d:\node_modules\blink-diff\bin\blink-diff --verbose --threshold-
type percent --threshold 0% --output compare1.png previous_release1.png next_release1.png
Blink-Diff 1.0.13
Copyright (C) 2014 Yahoo! Inc.
Images are visibly different
29 pixels are different
Wrote differences to compare1.png
Time: 498.177ms
Differences: 29 (0%)
FAIL

Comparison not accurate

When I use BlinkDiff (in combination with PixDiff) and I compare a "small" baseline image with the actual taken image I get a failure. This is also what I expect. But when I look at the diff it doens't fail on the actual thing I'd expect, all the text should fail.

I've tested this with all the possible combinations and parameters I can adjust with BlinkDiff

  • hShift / vShift / hideShift
  • perceptual (didn't work because of issues with gamma, see the PR)
  • delta

But the result is still not accurate enough.
Baseline:
dangeralert-compare-fail-chrome-1440x900-dpr-1

Actual screenshot:
dangeralert-compare-fail-chrome-1440x900-dpr-1

Comparison result:
dangeralert-compare-fail-chrome-1440x900-dpr-1

I know it's a different library, but when I use the online version of Resemble I get this output (with the defaults on)

image

Any ideas?

Error with perceptual mode

TypeError: Cannot read property 'R' of undefined
    at Object._correctGamma (/project/node_modules/blink-diff/index.js:933:21)
    at Object._getColor (/project/node_modules/blink-diff/index.js:909:17)
    at Object._pixelCompare (/project/node_modules/blink-diff/index.js:1119:19)
    at Object._compare (/project/node_modules/blink-diff/index.js:1191:29)
    at Object.<anonymous> (/project/node_modules/blink-diff/index.js:432:18)
    at /project/node_modules/promise/lib/core.js:33:15
    at flush (/project/node_modules/asap/asap.js:27:13)
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)
new BlinkDiff({
  hideShift: true,  // hide anti-aliasing differences
  imageA: imageA,
  imageB: imageB,
  perceptual: true
})

Support for ignoring pixel region

Would be great if blinkdiff supported ignoring pixel regions for such instances that there is dynamic content like a date or time displayed.

Something like:

var blinkDiff = new BlinkDiff({
    imageAPath: './imageA.png',
    imageBPath: './imageB.png',
    pixelIgnoreRegion: [
        {x: 10, y: 10, width: 20, height: 10},
        {x: 43, y: 53, width: 20, height: 10}
    ]
});
    _pixelCompare: function (imageA, imageB, imageOutput, deltaThreshold, pixelIgnoreRegion, width, height, outputMaskColor, outputShiftColor, backgroundColor, hShift, vShift, perceptual, gamma) {
        var difference = 0,
            i,
            x, y,
            delta,
            color1, color2,
            ignore = {};

        // build a hash lookup table
        for (i = 0; i < pixelIgnoreRegion.length; i++) {
            for (x = pixelIgnoreRegion[i].x; x < pixelIgnoreRegion[i].width; x++) {
                ignore[x] = []; // y column list for x row
                for (y = pixelIgnoreRegion[i].y; y < pixelIgnoreRegion[i].height; y++) {
                    ignore[x].push(y);
                }
            }
        }

        for (x = 0; x < width; x++) {
            for (y = 0; y < height; y++) {

                // Find if x is in ignore hash keys
                if (ignore[x]) {
                    // Find if y is in ignore list
                    if (ignore[x].indexOf(y) != -1){
                        continue; // skip pixel
                    }
                }

                i = imageA.getIndex(x, y);

Support for cropping imageB

Would be great if blinkdiff supported image cropping so that for example a small image could be compared with a cropped region of a larger image like a screenshot.

Something like:

function BlinkDiff (options) {

    this._imageCropRegion = options.imageCropRegion || {};

}
    run: function (fn) { 
        ...
            }.bind(this)).then(function (imageB) {
                this._imageB = imageB;

                if (Object.keys(this._imageCropRegion).length > 0) {
                    this._crop(this._imageB, this._imageCropRegion);
                }

                this._clip(this._imageA, this._imageB);
      ...
    },
    /**
     * Crops the source image to the bounds of rect
     *
     * @private
     * @method _crop
     * @param {PNGImage} image Source image
     * @param {object} rect Values for rect
     * @param (int} rect.left Left value of rect
     * @param (int} rect.top Top value of rect
     * @param (int} rect.width Width value of rect
     * @param (int} rect.height Height value of rect
     */
    _crop: function (image, rect) {

        if ((rect.left + rect.width) <= image.getWidth() && (rect.top + rect.height) <= image.getHeight()) {

            this.log("Cropping from " + rect.left + "," + rect.top + " by " + rect.width + " x " + rect.height);

            image.clip(rect.left, rect.top, rect.width, rect.height);
        }
    },

showing "real" diffs?

Pixel diffing is nice, but is there a way to tell this library that I care about "what is different" and not "highlighting the entire document just because there's extra vertical whitespace relatively high up in the image"?

For example, if I have two screenshots of a webpage, one with body { padding-top: 20px; } and one with body { padding-top: 20em; } then the only difference is going to be the extra whitespace. Everything else is identical, so having the entire image flagged as "diff" would be wrong (think of it as a github diff: a change that adds the letter a to the start of a README.md does not change the entire document. All it does is add an a, the rest of the document is still the same as before).

Is there a way to tell blink-diff to find diffs but with maximum shift detection?

Ignores completely new additions

... that are beyond the boundaries of imageA.

For example, with this code:

new BlinkDiff({
  hideShift: true,  // hide anti-aliasing differences (from composited image)
  imageA: imageA,
  imageB: imageB
})
.run((error, result) => console.log(result.differences);

... these two images result in a logged 0;

imageA:
imageA
imageB:
imageB

Support loading image from buffer

Would be great if blinkdiff would support loading an image from a buffer such as webdriver screenshots without requiring libs.

Example:

    /**
     * Loads the image from filesystem or loads the image from buffer
     *
     * @method _loadImage
     * @param {string} path
     * @param {PNGImage} image
     * @return {PNGImage|Promise}
     * @private
     */
    _loadImage: function (path, image) {
        if (image) {
            return Promise.denodeify(PNGImage.loadImage)(image);
        } else {
            return Promise.denodeify(PNGImage.readImage)(path);
        }
    },

Then we could do something like:

browser.takeScreenshot().then(function (image) {
    return new BlinkDiff({
            imageAPath: './image.png',
            imageB: new Buffer(image, 'base64')
        }).runWithPromise();
    }).then(function(result) {
        console.log(result);
    });
});

threshold percentage value seems to be getting ignored

I am comparing two images and passing parameters like '--threshold-type' percent & '--threshold' somevalue to Pass/Fail comparison on base of threshold .
However it seems threshold value is not getting honored

D:\>node d:\node_modules\blink-diff\bin\blink-diff --verbose --threshold-
type percent --threshold 0.001% --output compare1.png previous_release1.png next_release1.png
Blink-Diff 1.0.13
Copyright (C) 2014 Yahoo! Inc.
Images are similar
386 pixels are different
Wrote differences to compare1.png
Time: 833.052ms
Differences: 386 (0.05%)
PASS

However when I pass threshold as 0% (--threshold 0%) , it works as expected and FAILs comparison when difference is > 0%.

D:\>node d:\node_modules\blink-diff\bin\blink-diff --verbose --threshold-
type percent --threshold 0% --output compare1.png previous_release1.png next_release1.png
Blink-Diff 1.0.13
Copyright (C) 2014 Yahoo! Inc.
Images are visibly different
386 pixels are different
Wrote differences to compare1.png
Time: 846.282ms
Differences: 386 (0.05%)
FAIL

Error: ERROR: Unsupported bit depth 4

    at Object.<anonymous> (/project/node_modules/blink-diff/index.js:355:10)
    at .<anonymous> (/project/node_modules/pngjs-image/index.js:28:12)
...

Image A:
Image A

Image B:
Image B

Could this be related to #32 ?

Performance test ?

Could you also implement small performance test, how the tool is performing with different variety of image resolutions ? (example 100px x 100px; 300px x 300px; 1024px x 768px)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.