Comparing Images

Grafika can compare how similar two images are and can also determine if two images are equal.

Finding Similarity

Finding similarity between two images using the compare() method:

require_once 'path/to/grafika/src/autoloader.php'; // Automatically load our needed classes

use Grafika\Grafika; // Import package

$editor = Grafika::createEditor(); // Create editor

$hammingDistance = $editor->compare( "image1.jpg", "image-2.jpg" );

The compare method will return a hamming distance. The hamming distance determines how similar two images are. A value of 0 indicates a likely similar picture. A value between 1 and 10 is potentially a variation. A value greater than 10 is likely a different image.

Examples:
Type Image Hamming Distance
Base Image base N/A
Grayscaled gray 0
Dithered dither 0
Smaller,
Watermarked
water 1
Cropped
Note: If you wish to test if an image is cropped try setting the threshold to 26. That means check if the hamming distance is <= 26.
cropped 23
Totally Different Image diff 35

Checking Equality

Grafika can also do a pixel by pixel comparison to determine if two images are exactly the same using the equal() method:

require_once 'path/to/grafika/src/autoloader.php'; // Automatically load our needed classes

use Grafika\Grafika; // Import package

$editor = Grafika::createEditor(); // Create editor

$result = $editor->equal( "image1.jpg", "image-2.jpg" ); // Returns true if images are equal or false if not

This will return true if both images have exactly the same pixels.

It will compare if the two images are of the same width and height. If the dimensions differ, it will return false. If the dimensions are equal, it will loop through each pixels. If one of the pixel don't match, it will return false. The pixels are compared using their RGB (Red, Green, Blue) values.

equal() is expensive the larger the image. Use it when you absolutely need to check if two images are exactly the same. Otherwise you're better off using compare()