# Published on Maven Central and jCenter Java Library that compares 2 images with the same sizes and shows the differences visually by drawing rectangles. Some parts of the image can be excluded from the comparison. Can be used for automation qa tests.

##### Overview

Published on Maven Central and jCenter Java Library that compares 2 images with the same sizes and shows the differences visually by drawing rectangles. Some parts of the image can be excluded from the comparison. Can be used for automation qa tests. The Usages of the image-comparison can be found here Usage Image Comparison

• Implementation is using only standard core language and platform features, no 3rd party libraries and plagiarized code is permitted.

• Pixels (with the same coordinates in two images) can be visually similar, but have different values of RGB. 2 pixels are considered to be "different" if they differ more than pixelToleranceLevel(this configuration described below) from each other.

• The output of the comparison is a copy of actual images. The differences are outlined with red rectangles as shown below.

• No third party libraries or borrowed code are in usage.

• Some parts of the image can be excluded from the comparison and drawn in the result image.

Article about growing image-comparison on habr: How did the test task become a production library

## Configurations

Property Description
threshold The threshold which means the max distance between non-equal pixels. Could be changed according size and requirements to the image.
rectangleLineWidth Width of the line that is drawn the rectangle.
destination File of the result destination.
minimalRectangleSize The number of the minimal rectangle size. Count as (width x height). By default it's 1.
maximalRectangleCount Maximal count of the Rectangles, which would be drawn. It means that would get first x biggest rectangles. Default value is -1, that means that all the rectangles would be drawn.
pixelToleranceLevel Level of the pixel tolerance. By default it's 0.1 -> 10% difference. The value can be set from 0.0 to 0.99.
excludedAreas ExcludedAreas contains a List of Rectangles to be ignored when comparing images.
drawExcludedRectangles Flag which says draw excluded rectangles or not.
fillExcludedRectangles Flag which says fill excluded rectangles or not.
percentOpacityExcludedRectangles The desired opacity of the excluded rectangle fill.
fillDifferenceRectangles Flag which says fill difference rectangles or not.
percentOpacityDifferenceRectangles The desired opacity of the difference rectangle fill.
allowingPercentOfDifferentPixels The percent of the allowing pixels to be different to stay MATCH for comparison. E.g. percent of the pixels, which would ignore in comparison. Value can be from 0.0 to 100.00

## Release Notes

Can be found in RELEASE_NOTES.

## Usage

#### Maven

<dependency>
<groupId>com.github.romankh3</groupId>
<artifactId>image-comparison</artifactId>
<version>4.3.0</version>
</dependency>

compile 'com.github.romankh3:image-comparison:4.3.0'

#### To compare two images programmatically

class Example {
public static void main( String[] args ) {
// load the images to be compared

// where to save the result (leave null if you want to see the result in the UI)
File resultDestination = new File( "result.png" );

//Create ImageComparison object for it.
ImageComparison imageComparison = new ImageComparison( expectedImage, actualImage, resultDestination );

//Can be used another constructor for it, without destination.
new ImageComparison("expected.png", "actual.png");
//or
new ImageComparison(expectedImage, actualImage);

//Also can be configured BEFORE comparing next properties:

//Threshold - it's the max distance between non-equal pixels. By default it's 5.
imageComparison.setThreshold(10);
imageComparison.getThreshold();

//RectangleListWidth - Width of the line that is drawn in the rectangle. By default it's 1.
imageComparison.setRectangleLineWidth(5);
imageComparison.getRectangleLineWidth();

//DifferenceRectangleFilling - Fill the inside the difference rectangles with a transparent fill. By default it's false and 20.0% opacity.
imageComparison.setDifferenceRectangleFilling(true, 30.0);
imageComparison.isFillDifferenceRectangles();
imageComparison.getPercentOpacityDifferenceRectangles();

//ExcludedRectangleFilling - Fill the inside the excluded rectangles with a transparent fill. By default it's false and 20.0% opacity.
imageComparison.setExcludedRectangleFilling(true, 30.0);
imageComparison.isFillExcludedRectangles();
imageComparison.getPercentOpacityExcludedRectangles();

//Destination. Before comparing also can be added destination file for result image.
imageComparison.setDestination(resultDestination);
imageComparison.getDestination();

//MaximalRectangleCount - It means that would get first x biggest rectangles for drawing.
// by default all the rectangles would be drawn.
imageComparison.setMaximalRectangleCount(10);
imageComparison.getMaximalRectangleCount();

//MinimalRectangleSize - The number of the minimal rectangle size. Count as (width x height).
// by default it's 1.
imageComparison.setMinimalRectangleSize(100);
imageComparison.getMinimalRectangleSize();

//Change the level of the pixel tolerance:
imageComparison.setPixelToleranceLevel(0.2);
imageComparison.getPixelToleranceLevel();

//After configuring the ImageComparison object, can be executed compare() method:
ImageComparisonResult imageComparisonResult = imageComparison.compareImages();

//Can be found ComparisonState.
ImageComparisonState imageComparisonState = imageComparisonResult.getImageComparisonState();

//And Result Image
BufferedImage resultImage = imageComparisonResult.getResult();

//Image can be saved after comparison, using ImageComparisonUtil.
ImageComparisonUtil.saveImage(resultDestination, resultImage);
}
}

## Demo

Demo shows how image-comparison works.

## Code of Conduct

This project is Apache License 2.0 - see the LICENSE file for details

• #### [QUESTION] Get result of image comparison using Java

I've carefully checked your demo sample code but it's not clear how programmatically check if the result of comparison true or false? Please, let me know.

Jeff

question
• #### StackOverflowError when compared 2 images with a little big different area.

Hello @romankh3 I got a Exception: Exception in thread "main" java.lang.StackOverflowError at ua.comparison.image.ImageComparison.joinToRegion(ImageComparison.java:110) when compared 2 images with a little big different area. Image resolution of both are : 1920 * 931, as attached image1: image2:

bug help wanted
opened by alexbai326 17
• #### Logo proposal

Hello @romankh3, i am a graphic designer. I would like to know if you would be interested in me making a logo for this project. If you would have me, i would make a logo for you, and it's free.

opened by dee-y 14
• #### Add test for images with different jpeg-compression level

Hello Roman! Can you, please, add tests for images with different jpeg-compression? I believe many people who often work with jpeg will have this question. When someone made changes in the image in programs like Photoshop or Gimp and save image as jpg file, s/he needs to choose the compression level (good quality and large file weight or visa versa, from 0 to 100%). The compression algorithm makes some changes in pixels of the original image. When compression is near 60-70 quality lowering not much visible for human eyes tho, but still can be tangible for your algorithm even with a 10% sensitivity threshold. So the question is will compression be a problem? Will high compression prevent your library work as expected?

I made some images for 4 tests. Every test is in separate dir which contains an original image that needs to be compared with other 3-4 one by one. Each image has a different quality: original - original with some changes - 60 - 20 - 0 (it's written in the filename). Images in the first dir don't have any 'human-made' difference just compression by itself. And the last test is for text-image, I think it's a very interesting case too. images_for_test.zip

good first issue
opened by Hexronimo 12
• #### Questions about flaky comparison results

Hello,

I use your tool and it had worked great for me until now. Here Is my scenario. I have an app that is going through an upgrade.

1. I make screenshots using Selenium for several pages and store them as baseline images (before the upgrade).
2. I run my app after the upgrade and make screenshots of the same pages
3. I compare on the fly each new and old/baseline pages and use .setAllowingPercentOfDifferentPixels(10)
4. Sometimes my result is MATCH or MISMATCH or SIZE_MISMATCH and its' random

What can you suggest to make it work stable? Oh, differences in fact are minimal. I use the Chrome browser to run my app

Your help will be greatly appreciated

Jeff

question
• #### Allow program to run as a traditional CLI

In this PR, I 've added a simple ArgsParser class to allow user to pass in options to the program, so that they can compare two images from image files they pass in as arguments. The user can also give a file where the result should be saved to. Not providing an output file makes the program open the UI, as it does currently.

I also made the jar created by Gradle be runnable (by adding the Main-Class entry to the manifest), so now you can run the program with java -jar image-comparison.jar.

opened by renatoathaydes 11
• #### [QUESTION] getDifferencePercent meaning

Hi @romankh3 ! Could you please clarify how the differencePercent is calculated? I compare these 2 images: and and got the result: Then I trying to use something like: return (imageComparisonResult.getDifferencePercent() <= diffPercentage)

I expected getDifferencePercent is calculated like total square of all difference rectangles vs image square, like: Sum (S<i = 1..n> S) / S ~ 15% for my images.

But surprisingly I got 0.0! Could you please clarify where I'm wrong? Thanks in advance!

question
opened by dmiroshnyk 10
• #### StackOverFlow error

Hi, Whenever I use an image that is not small, I'm getting a StackOverFlow error on the recursion. Any ideas? thoughts?

Thanks.

opened by Dgotlieb 10
• #### Added option to resize image if size mis-match

I am using the the image-comparison library in mobile visual test automation and in some cases even with size mismatch it's practical to do the comparison despite the size difference that's in case of the design will keep it's ratio.

another case the difference sometimes could be small number of pixels so that I find it very useful that we have an option to resize the actual image to the expected dimensions and then do the comparison.

wating for your opinion and many thanks.

-Added overloaded function of compareImages(boolean resizeIfSizeMisMatch) to enable resizing to expected dimensions. -Added resize function to utils.

enhancement
opened by KhaldAttya 10
• #### [IMPROVEMENT] fill excluded rectangles with transparent green

I add many excluded areas to my images and find it very useful that they appear as green rectangles on the results image. I often need to define long exclusions along edges of the image. In those cases, looking at the resulting image, it is not easy to determine which areas have been excluded, partly due to the fact that the green lines along the edges are cropped out of the picture.

It would be less ambiguous if there was an option to fill the the green rectangles with a transparent green fill.

enhancement
opened by MrMisterG 9
• #### [BUG] Different images are considered equal

Description I'm using this project as one of the image comparison methods being used in the EchoSVG tests, and noticed that one of the tests that should fail was systematically passing. For example, the following two images are identical (match) according to this project (version 4.4.0):

The last color is not the same (#c20272 vs #df0272), and the text located next to that color also varies (the images are transparent, so if you are using Github's dark theme you may need to download them and open elsewhere to read it).

To Reproduce To be sure, I ran this separate piece of code to compare the two images (in case it was my testing infrastructure screwing things up):

BufferedImage expectedImage = ImageComparisonUtil.readImageFromResources("C:\\path\\to\\domSVGColor.png");
ImageComparison comparison = new ImageComparison(expectedImage, actualImage);
ImageComparisonResult result = comparison.compareImages();
assertTrue(ImageComparisonState.MATCH != result.getImageComparisonState());


and it failed (the different images do match). The above snippet is the obvious reproducer.

Expected behavior The images are different and should not match.

Desktop

• OS: Windows 10
• Image-comparison version: 4.4.0.
bug
opened by carlosame 1
• #### [FEATURE] move from bintray

Is your feature request related to a problem? Please describe. A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like A clear and concise description of what you want to happen.

Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

enhancement
opened by romankh3 0

Hi Roman,

I'm very happy with your tool but we are moving towards Javascript/Typescript. Is it possible for you to build a jar with parameters input? So, I'll be able to invoke it from Typescript? Please, let me know

Thanks

Jeff

question
• #### [IMPROVEMENT] Diff between pixels

Moved from another issue

Why diff between pixels is calculated like (pixel2RGB - pixel1RGB)? For example, we have pixel2 - white. Diff vs pixel1 depends on pixel1 RGB color. So, diff vs red pixel will be less than vs blue. I don't understand the reason of this. For example, if I convert my image with google and change all red colors to blue and ask to recalculate diff (let's imagine the bug is fixed) - the diff percentage return another value which looks having no sense because the result file will look identically. IMHO, the diff between single pixel should be normalized to 0 (no diff) or 1(diff) and formula should look like: (<# of all different pixels> / <# of all pixels>) * 100. What do you think about it?

enhancement
opened by dmiroshnyk 0
• #### [IMPROVEMENT] Fix all the barges.

** Describe your idea of the improvement ** some of them don't work at all and need to be fixed.

enhancement
opened by romankh3 0
• #### [IMPROVEMENT] Create development guidelines for preparing to release process

** Describe your idea of the improvement ** Due to the fact, that there is no document for the release process, some issues/bugs can be created with it.

enhancement
opened by romankh3 0

** Describe your idea of the improvement ** Due to the fact, that in this version would add simpleComparison method, it would be really good if we create load tests to see the difference between compareImages() and simpleComparison() methods.

enhancement
opened by romankh3 0
• #### [IMPROVEMENT] FAQ wiki page

** Describe your idea of the improvement ** Due to the fact, that exist a lot of questions about using image comparison, I’d like to add wiki page for it.

enhancement
opened by romankh3 0
• #### [IMPROVEMENT] Add wiki-page for explaining how excluded areas work

how can I set exclusion rectangles? What measures can I use (mm, pixels, etc)? Can I somehow use your tool to compare the same web pages but in different languages for localization testing automation? I wasn't able to find any code examples> Please, let me know.

Jeff

Originally posted by @jeffradom in https://github.com/romankh3/image-comparison/issues/171#issuecomment-596132296

enhancement
opened by romankh3 0
• #### [IMPROVEMENT] Move publishing via pom.xml

** Describe your idea of the improvement ** Due to the reason, that GitHub supports pom.xml, but doesn't build.gradle, image-comparison must be moved to Maven and pom.xml

enhancement
opened by romankh3 9
• #### v4.4.0(Mar 28, 2021)

⭐️ New Features

#205: based on #204 discussion, which created @woosyume added a new feature - update rectangle line color.

I'd like to say thank you for your contributions: @woosyume for a new feature that suggested and implemented

Source code(tar.gz)
Source code(zip)
• #### v4.3.1(Mar 13, 2021)

🐞 Bug Fixes image-comparison became better:

Fixed bug #201 - problem with comparing totally different pictures.

❤️ Contributors I'd like to say thank you for your contributions:

@HoverCatz - thank you for your report of a new bug.

Source code(tar.gz)
Source code(zip)
• #### v4.3.0(Sep 8, 2020)

⭐️ New Features

• #192: Include rectangles with difference in comparison results (@akondas)
• Improved and added missing tests (@AnthonyJungmann, @romankh3) 🐞 Bug Fixes
• #196 [BUG] Set 0.0 difference percent for MISMATCH (@romankh3)

❤️ Contributors I'd like to say thank you for your contributions:

• @akondas for a new feature
• @AnthonyJungmann for a missing tests
• @dmiroshnyk for finding a bug with differencePercent
Source code(tar.gz)
Source code(zip)
• #### v4.2.1(Apr 17, 2020)

🐞 Bug Fixes image-comparison became better:

• Fixed bug #180 - problem with ImageComparisonUtil.readFromResources method.

❤️ Contributors I'd like to say thank you for your contributions:

• @mrgoroua - thank you for your report a new bug.
Source code(tar.gz)
Source code(zip)
• #### v4.2.0(Mar 11, 2020)

New Features

• #175: added the ability to ignore some percent of differences for comparison.

Contributors I'd like to say thank you for your contributions

Source code(tar.gz)
Source code(zip)
• #### v4.1.0(Jan 29, 2020)

New Features

• #167 fill excluded rectangles with transparent green(@MrMisterG)

Contributors

I'd like to say thank you for your contributions:

• @MrMisterG - for proposing new feature and developing it with respect to the development process.
Source code(tar.gz)
Source code(zip)
• #### v4.0.1(Jan 11, 2020)

⭐️ New Features

• #154: migrated to JUnit 5(@Wandmalfarbe)

🐞 Bug Fixes

• #165: fixed bug with maximal rectangle count(@Hexronimo)

❤️ Contributors I'd like to say thank you for your contributions:

• @Wandmalfarbe for providing the solution for #154
• @Hexronimo for finding a bug #165
Source code(tar.gz)
Source code(zip)
• #### v4.0.0(Dec 9, 2019)

⭐️ New Features

• refactored drawRectangles method due to SRP.
• optimized isDifferentPixels to improve the algorithm.
• moved to Apache License 2.0
• removed Point and used java.awt.Point instead
• removed commandLine usage
• renamed ComparisonResult to ImageComparisonResult
• renamed ComparisonState to ImageComparisonState
• added own RuntimeException for wrapping checked exception
• added Gitter chat for communication.

❤️ Contributors @mw79, @xSAVIKx - thanks for ideas, which you provided for this release.

Source code(tar.gz)
Source code(zip)
• #### v3.3.1(Nov 4, 2019)

🐞 Bug Fixes

• #134: If the image is different in a line in 1 px, ComparisonState is always MATCH(@grigaman)
• #136: deepCopy method throws IllegalArgumentException on shared BufferedImage(@grigaman)

❤️ Contributors

I'd like to say thank you for your contributions:

• @grigaman
Source code(tar.gz)
Source code(zip)
• #### v3.3.0(Sep 2, 2019)

⭐️ New Features

• Added option to get the pixels difference percentage between images in case of SIZE_MISMATCH.(@KhaldAttya)

🐞 Bug Fixes

• #89: Fixed NPE for default run from the command line(@KyryloKh)

❤️ Contributors I'd like to say thank you for your contributions:

• @KhaldAttya
• @KyryloKh

:octocat: Reviewers

• @SmashSide
• @kremenec
Source code(tar.gz)
Source code(zip)
• #### 3.2.0(Aug 4, 2019)

⭐️ New Features

• Added ability to change pixel tolerance level.
• Improved algorithm to make it faster.
• Researched JPEG images, all work as expected.
Source code(tar.gz)
Source code(zip)

• #### 3.1.0(Jun 4, 2019)

⭐️ New Features

• Added the ability to draw excluded areas on the result image. Rectangles with the differences drawing RED color. Rectangles of the excluded areas - GREEN color.

• Fixed root problem on the algorithm.

• Added returning this for setters in ImageComparison and ComparisonResult.

• renamed image1 => expected and image2 => actual.

Source code(tar.gz)
Source code(zip)

• #### 3.0.0(May 29, 2019)

⭐️ New Features

• Added ComparisonResult as a returning value for comparing. It contains:
• image1
• image2
• ComparisonState, with conditions MATCH, MISMATCH, SIZE_MISMATCH
• Result image, only if ComparisonState is MISMATCH. When it is MATCH or SIZE_MISMATCH no needs to create result image.
• added minimalRectangleSize and maximalRectangleCount(sorted by rectangle size).
• Added more tests to cover more test cases.
• Refactored CommandLineUsage, moved main() method to separated class.(@ak98neon)
• Added ExcludedAreas functionality, which helps to exclude some parts of the image.(@mkytolai)

❤️ Contributors I'd like to say thank you for your contributions

• @mkytolai
• @ak98neon

:octocat: Reviewers

• @ak98neon
• @smashside
• @kremenec
• @KyryloKh
Source code(tar.gz)
Source code(zip)
• #### 2.2.0(May 14, 2019)

⭐️ New Features

• Added ability to customize rectangle line width(@mkytolai).
• Moved the main method from Image Comparison to own class(@ak98neon).
• Added Code of Conduct and Contributing pages(@romankh3).

🐞 Bug Fixes

❤️ Contributors I'd like to thank all the contributors who helped to improve it:

• @mkytolai
• @ak98neon
Source code(tar.gz)
Source code(zip)
• #### 2.1.0(Apr 15, 2019)

⭐️ New Features

• Published the project to JCenter, MavenCentral
• Update packages related to groupId.

🐞 Bug Fixes

All the bugs were successfully fixed on 2.0.2 version.

❤️ Contributors

I'd like to say thank @renatoathaydes! He helped me to publish image-comparison.

Source code(tar.gz)
Source code(zip)
• #### 2.0.2(Apr 10, 2019)

⭐️ New Features

• Improved comparison algorithm.
• Improved tests cases and test coverage to 100%.

🐞 Bug Fixes

• #11: Rectangles can overlap and be included one-into-one.
• #21: StackOverflowError when compared 2 images with a little big different area.
• #43: Added extra overlapping based on fixing #21 bug.

❤️ Contributors I'd like to thank all the contributors who helped to improve it!

• @renatoathaydes
• @alexbai326
• @pvarenik
• @gao2q
• @kremenec
• @dee-y
Source code(tar.gz)
Source code(zip)

• #### v1.0(Aug 10, 2017)

The program in Java that compares any 2 images and shows the differences visually by drawing rectangles.

• Implementation is using only standard core language and platform features, no 3rd party libraries and plagiarized code is permitted.
• Pixels (with the same coordinates in two images) can be visually similar, but have different values of RGB. We are only consider 2 pixels to be "different" if the difference between them is more than 10%.
• The output of the comparison is a copy of one of the images image with differences outlined with red rectangles as shown below.
• No third party libraries and borrowed code are not using.
Source code(tar.gz)
Source code(zip)
###### Roman Beskrovnyi
Sr. Software Engineer. Open source contributor. Happy father of two. Join IT telegram-channel https://t.me/romankh3
###### Simple Java image-scaling library implementing Chris Campbell's incremental scaling algorithm as well as Java2D's "best-practices" image-scaling techniques.

imgscalr - Java Image-Scaling Library http://www.thebuzzmedia.com/software/imgscalr-java-image-scaling-library/ Changelog --------- 4.2 * Added sup

1.1k Aug 24, 2021
###### TwelveMonkeys ImageIO: Additional plug-ins and extensions for Java's ImageIO

About TwelveMonkeys ImageIO is a collection of plugins and extensions for Java's ImageIO. These plugins extend the number of image file formats suppor

1.3k Sep 17, 2021
3 May 13, 2021
###### Open source Picture to text, text to Picture app

Pic SMS App Pic SMS is a free open source app. With Pic SMS, you can: convert pictures into text parts and send as SMS convert text parts into a pictu

15 Sep 14, 2021
###### Diagrams as code is a term used for storing the source of a diagram image as a text file.

Diagrams as code Diagrams as code is a term used for storing the source of a diagram image as a text file. Examples are architecture diagrams, or diag

18 Sep 10, 2021
###### Java interface to OpenCV, FFmpeg, and more

JavaCV Commercial support: Introduction JavaCV uses wrappers from the JavaCPP Presets of commonly used libraries by researchers in the field of comput

5.3k Sep 19, 2021

767 Sep 12, 2021
###### Thumbnailator - a thumbnail generation library for Java

March 11, 2021: Thumbnailator 0.4.14 has been released! See Changes for details. Thumbnailator is now available through Maven! What is Thumbnailator?

3.8k Sep 17, 2021
###### VisionCamera Frame Processor Plugin to label images using MLKit Vision

vision-camera-image-labeler A VisionCamera Frame Processor Plugin to label images using MLKit Vision Image Labeling. Installation npm install vision-c

46 Sep 14, 2021
###### ZXing ("Zebra Crossing") barcode scanning library for Java, Android

Project in Maintenance Mode Only The project is in maintenance mode, meaning, changes are driven by contributed patches. Only bug fixes and minor enha

28.4k Sep 13, 2021
###### Custom Image Server for use with ShareX

rImageServer How to use: Normal Instalation: Download .jar Start: javar -jar [filename].jar Edit: imageserver.propierties Check if web works -> Go to

13 Aug 27, 2021
###### Java JNA wrapper for Tesseract OCR API

Tess4J A Java JNA wrapper for Tesseract OCR API. Tess4J is released and distributed under the Apache License, v2.0. Features The library provides opti

1k Sep 16, 2021
###### 必应每日超清壁纸（4K）

Bing Wallpaper Today: Lençóis Maranhenses National Park in the state of Maranhão, Brazil (© WIN-Initiative/Getty Images) 2021-04-03 download 4k 2021-0

210 Sep 13, 2021
###### Anthos Edge Use Cases for bringing apps and computation closer to the location where the action is, to improve response times and save bandwidth.

Anthos Bare Metal Edge Use Cases Edge computing is a distributed computing paradigm that brings computation and data storage closer to the location wh

3 Sep 15, 2021
###### Pw0 Framewrok - magical android pentest app 🔮! Pixie Dust, Handshakes, Deauth, Nmap, Port scanner and more!

Pw0 Framework Pw0 Framewrok - magical android pentest app ?? ! Features: Pixie Dust Handshakes Deauth Nmap Port scanner and more! Version: 0.2 Beta Au

12 Sep 1, 2021
###### Traditional roguelike game with pixel-art graphics and simple interface

Traditional roguelike game with pixel-art graphics and simple interface

1.4k Sep 10, 2021