Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

- add average color comparison #7

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
484 changes: 238 additions & 246 deletions composer.lock

Large diffs are not rendered by default.

71 changes: 67 additions & 4 deletions src/ImageComparator.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,11 @@ public function compare(
): float {
$hash1 = $this->hashImage($sourceImage); // this one should never be rotated
$hash2 = $this->hashImage($comparedImage, $rotation);
$color1 = $this->getAverageRGB($sourceImage);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@D4lv1k I'd suggest calculating color similarity to a private function

$color2 = $this->getAverageRGB($comparedImage);
$similarityColor = $this->calculateSimilarity($color1, $color2);

return $this->compareHashes($hash1, $hash2, $precision);
return $this->compareHashes($hash1, $hash2, $precision, $similarityColor);
}

/**
Expand Down Expand Up @@ -281,7 +284,7 @@ private function normalizeAsResource(string|GdImage $image): GdImage
* @throws MathException
* @throws NumberFormatException
*/
private function compareHashes(array $hash1, array $hash2, int $precision): float
private function compareHashes(array $hash1, array $hash2, int $precision, float $colorSimilarity): float
{
if (count($hash1) !== count($hash2)) {
throw new InvalidArgumentException('Hashes must be of the same length.');
Expand All @@ -296,10 +299,12 @@ private function compareHashes(array $hash1, array $hash2, int $precision): floa
}
}

$percentage = $similarity->dividedBy($totalBits, $precision, RoundingMode::HALF_UP)
$hashSimilarity = $similarity->dividedBy($totalBits, $precision, RoundingMode::HALF_UP)
->multipliedBy(BigDecimal::of(100));
$hashSimilarity = BigDecimal::of($hashSimilarity)->multipliedBy($colorSimilarity);
$hashSimilarity = $hashSimilarity->toScale($precision, RoundingMode::HALF_UP);

return $percentage->toFloat();
return $hashSimilarity->toFloat();
}

/**
Expand Down Expand Up @@ -347,4 +352,62 @@ private function processImagePixels(

return $pixels;
}

private function calculateRGBDistance(array $color1, array $color2): float
{
$r1 = $color1['r'];
$g1 = $color1['g'];
$b1 = $color1['b'];

$r2 = $color2['r'];
$g2 = $color2['g'];
$b2 = $color2['b'];

return sqrt(pow($r1 - $r2, 2) + pow($g1 - $g2, 2) + pow($b1 - $b2, 2));
}

private function calculateSimilarity(array $color1, array $color2): float
{
$maxRGBDifference = sqrt(pow(255, 2) + pow(255, 2) + pow(255, 2));
$distance = $this->calculateRGBDistance($color1, $color2);

return 1 - ($distance / $maxRGBDifference);
}

/**
* @throws ImageResourceException
*/
private function getAverageRGB(
GdImage|string $image,
int $size = 8
): array {
$image = $this->normalizeAsResource($image);
$imageResized = imagescale($image, $size, $size);

$width = imagesx($imageResized);
$height = imagesy($imageResized);

$totalRed = $totalGreen = $totalBlue = 0;
$totalPixels = $width * $height;

for ($y = 0; $y < $height; $y++) {
for ($x = 0; $x < $width; $x++) {
$colorIndex = imagecolorat($imageResized, $x, $y);

$red = ($colorIndex >> 16) & 0xFF;
$green = ($colorIndex >> 8) & 0xFF;
$blue = $colorIndex & 0xFF;

$totalRed += $red;
$totalGreen += $green;
$totalBlue += $blue;
}
}

return [
'r' => round($totalRed / $totalPixels),
'g' => round($totalGreen / $totalPixels),
'b' => round($totalBlue / $totalPixels),
];
}
}
18 changes: 14 additions & 4 deletions tests/Unit/ImageComparatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,11 @@ public function testCompareRotated(): void

$result = $this->imageComparator->compare($image, $imageRotated, ImageRotationAngle::D90);

$this->assertSame(96.9, $result);
$this->assertSame(96.363, $result);

$result = $this->imageComparator->compare($image, $imageRotated, ImageRotationAngle::D90, 10);

$this->assertSame(96.875, $result);
$this->assertSame(96.3377374947, $result);
}

public function testCompareShouldThrowException(): void
Expand Down Expand Up @@ -110,7 +110,7 @@ public function testSquareImage(): void

$result = $this->imageComparator->compare('tests/images/flower2.jpg', $squareImage);

$this->assertSame(48.4, $result);
$this->assertSame(36.973, $result);
}

public function testHashImage(): void
Expand Down Expand Up @@ -259,7 +259,7 @@ public function testCompareWithBrightnessContrastAdjustment(): void

$result = $this->imageComparator->compare($image1, $image2);

$this->assertGreaterThan(70, $result);
$this->assertGreaterThan(55, $result);
}

public function testCompareBlurredImages(): void
Expand Down Expand Up @@ -289,6 +289,16 @@ public static function differentImagesProvider(): array
'image1' => 'tests/images/ebay-image2.png',
'image2' => 'tests/images/amazon-image2.png',
'expectedPercentage' => 60.00
],
'Similar image black and white' => [
'image1' => 'tests/images/black.png',
'image2' => 'tests/images/white.png',
'expectedPercentage' => 1.00
],
'Similar image red and blue' => [
'image1' => 'tests/images/red.png',
'image2' => 'tests/images/blue.png',
'expectedPercentage' => 20
]
];
}
Expand Down
Binary file added tests/images/black.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added tests/images/blue.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added tests/images/red.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added tests/images/white.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.