Selphiron
Selphiron

Reputation: 929

Measure similarity of two images in Java or ImageMagick

I have two different algorithms that take an image as input. The image has polygons of different colors. The algorithm "simplifies" these polygons (so that they have less corners and edges) and removes polygons, which are too small.

These two algorithms work differently and I want to know which one is actually better in terms of which one is closer to the original picture. I came across this but that is not quite what I was looking for.

These two images

image 1 , image 2

should have a similarity of 50%, but according to that algorithm their similarity is 80%.

I also found a tool called ImageMagick that can compare two images. But I am not sure what the meaning of the outputs is and how I can use them to solve my problem.

Upvotes: 3

Views: 4720

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207853

You would use ImageMagick like this to compare your two images:

compare -metric ae a.png b.png null:
1161

or, the longer form using convert

convert -metric ae a.png b.png -compare -format "%[distortion]" info:
1161

The -metric ae means "tell me the absolute error", i.e. the number of pixels that differ between the two images. In this case, the answer is 1161, which is exactly half the pixels, i.e. 50%.

If you specifically want 50% output, you can do the maths on the image dimensions with ImageMagick like this, if you use bash:

n=$(compare -metric ae a.png b.png null:)
identify -format "%[fx:$n*100/(w*h)]" a.png

or the longer form, using convert:

n=$(compare -metric ae a.png b.png null:)
convert -format "%[fx:$n*100/(w*h)]" a.png info:
50

If you are dealing with jpg images (and therefore lossy compression and artefacts) rather than png images, you may want to add in a fudge factor of a few percent, using the -fuzz parameter to allow almost identical pixels to count as being the same:

convert -fuzz 10% -metric ae ....

If you are unfortunate enough to have to use Windows, the way to do the above is arcane and unintelligible, but looks like this:

@echo off
for /f "tokens=1,2,3,*" %%G in ('convert -metric ae a.png b.png -compare -format "%%w %%h %%[distortion]" info:') DO set /a percent=(%%I * 100) /(%%G * %%H)
echo %percent%

Upvotes: 8

Related Questions