How to resolve the algorithm Percentage difference between images step by step in the Perl programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Percentage difference between images step by step in the Perl programming language
Table of Contents
Problem Statement
Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): The expected difference for these two images is 1.62125%
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Percentage difference between images step by step in the Perl programming language
Source code in the perl programming language
use Image::Imlib2;
my $img1 = Image::Imlib2->load('Lenna50.jpg') || die;
my $img2 = Image::Imlib2->load('Lenna100.jpg') || die;
my $w = $img1->width;
my $h = $img1->height;
my $sum = 0;
for my $x (0..$w-1) {
for my $y (0..$h-1) {
my ($r1, $g1, $b1) = $img1->query_pixel($x, $y);
my ($r2, $g2, $b2) = $img2->query_pixel($x, $y);
$sum += abs($r1-$r2) + abs($g1-$g2) + abs($b1-$b2);
}
}
printf "%% difference = %.4f\n", 100 * $sum / ($w * $h * 3 * 255);
use Imager;
use List::AllUtils qw(sum pairwise);
sub img_diff {
my ($file1, $file2) = @_;
my $img1 = Imager->new(file => $file1);
my $img2 = Imager->new(file => $file2);
my ($w1, $h1) = ($img1->getwidth, $img1->getheight);
my ($w2, $h2) = ($img2->getwidth, $img2->getheight);
if ($w1 != $w2 or $h1 != $h2) {
die "Can't compare images of different sizes";
}
my $sum = 0;
foreach my $y (0 .. $h1 - 1) {
foreach my $x (0 .. $w1 - 1) {
my @rgba1 = $img1->getpixel(x => $x, y => $y)->rgba;
my @rgba2 = $img2->getpixel(x => $x, y => $y)->rgba;
$sum += sum(pairwise { abs($a - $b) } @rgba1, @rgba2);
}
}
$sum / ($w1 * $h1 * 255 * 3);
}
printf "difference = %f%%\n", 100 * img_diff('Lenna50.jpg', 'Lenna100.jpg');
You may also check:How to resolve the algorithm Sierpinski arrowhead curve step by step in the REXX programming language
You may also check:How to resolve the algorithm Nim game step by step in the Go programming language
You may also check:How to resolve the algorithm Guess the number/With feedback step by step in the AWK programming language
You may also check:How to resolve the algorithm SHA-256 step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Smith numbers step by step in the C++ programming language