Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Matching Images

by virtualweb (Sexton)
on Nov 21, 2010 at 17:38 UTC ( #872801=perlquestion: print w/ replies, xml ) Need Help??
virtualweb has asked for the wisdom of the Perl Monks concerning the following question:

Hi:

I would like my script to compare two images and tell me if even one single pixel is slightly different in one of them. Also tell me if its width or height is different too.

Is there a library which already does this..??

I know about the file test operators. (-T for text files, -B for Binary, -s for size, -M last modified in days, -A last accessed in days), but I havent found any operator which can tell me if the pixels or width or height have been changed.

So far, besides using the test operators above, I'm opening both binary files , reading them into memory and comparing the output... but ofcourse this is not good enough I need better suggestions.

open (IMAGE1, "<image1.jpg") || die print"cant open image1.jpg"; $results1 = <IMAGE1>; close (IMAGE1); open (IMAGE2, "<image2.jpg") || die print"cant open image2.jpg"; $results2 = <IMAGE2>; close (IMAGE2); if ($results1 eq $results2){ print"both images are the same"; }

If you can help.. I'll appreciate it

Comment on Matching Images
Download Code
Re: Matching Images
by BrowserUk (Pope) on Nov 21, 2010 at 18:29 UTC

    This will do the job, including comparing different image formats provided they contain the same picture:

    #! perl -slw use strict; use GD; GD::Image->trueColor( 1 ); my $img1 = GD::Image->new( $ARGV[ 0 ] ); my $img2 = GD::Image->new( $ARGV[ 1 ] ); die "Different dimensions" unless $img1->width == $img2->width and $img1->height == $img2->height; my $raw1 = $img1->gd; my $raw2 = $img2->gd; die "images are different" unless $raw1 eq $raw2; print "Images are the same"; __END__ c:\test>cmpImages mandrill.jpg mandrill.png Images are the same

    But be aware, that images that look the same to the our eyes may be quite different in detail.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      > including comparing different image formats provided they contain the same picture

      Really? AFAIK png and jpg use compression methods resulting in unpredictable information loss. IMHO converting them to a raw format will not often produce identical data.

      Or am I missing a special magic feature?

      I think I would rather try to calculate a diff and test the average distance for a threshold passed. Not sure if the result of ->compare can be used for this.

      Cheers Rolf

        Really? IMHO png and jpg use compression methods resulting in unpredictable information loss. IMHO converting them to a raw format will not often produce identical data.

        Really. And to resolve your doubts please try it.

        The "secret" such as it is, is that the raw format used for the comparison is neither jpg nor png, but libgd's own internal format, which is an uncompressed, lossless format. The images of all formats supported by GD are converted fully expanded into this internal format, and it is this binary representation, returned by the $image->gd method that is being compared in the code I posted. As such, even individual pixel differences are detected.

        By way of demonstration, in my post above, I took a jpg image of a mandrill monkey and used an image editor to convert it to a compressed but lossless .png. I then compared those two images and no discrepancies were found.

        By way of further demonstration, using the slightly expanded version below, I then edited the ,png version by changing the color of a single pixel on the mandrill's nose, from it's original near white color to pure red. and then compared that against the original .jpg:

        c:\test>cmpImages mandrill.png mandrill-2.png images are different Process pixels? Difference at (665:482): [248 248 238] .v. [255 0 0]

        As you can see, that single pixel difference was correctly detected by the raw binary compare, and then subsequently isolated using a pixel-by-pixel comparison. Please try it to convince yourself that it is correct.

        But do bear in mind my warning above. If, for example, you were to take a ,png image and convert it to a lossy image format such as .jpg, then although the images may appear superficially similar to the human eye, they may be quite different in actuality. This due to the jpeg algorithms practice of substituting a single color for many, closely aligned but mathematically different colors in order to reduce palette sizes and aid compression.

        Such lossy transforms will be correctly detected as different, even though cursory, by-eye inspections might adjudge them to be the same.

        The expanded code:

        #! perl -slw use strict; use GD; GD::Image->trueColor( 1 ); my $img1 = GD::Image->new( $ARGV[ 0 ] ); my $img2 = GD::Image->new( $ARGV[ 1 ] ); die "Different dimensions" unless $img1->width == $img2->width and $img1->height == $img2->height; my $raw1 = $img1->gd; my $raw2 = $img2->gd; if( $raw1 ne $raw2 ) { print "images are different"; printf "Process pixels? "; <STDIN>; for my $y ( 0 .. $img1->height -1 ) { for my $x ( 0 .. $img1->width -1 ) { my $p1 = $img1->getPixel( $x, $y ); my $p2 = $img2->getPixel( $x, $y ); if( $p1 != $p2 ) { print "Difference at ($x:$y): [@{[ $img1->rgb( $p1 ) ] +}] .v. [@{[ $img2->rgb( $p2 ) ]}]"; } } } } else { print "Images are the same"; } __END__

        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.
        PNG is lossless. It's reason for being was to replace GIF, a lossless format.
Re: Matching Images
by kcott (Abbot) on Nov 21, 2010 at 18:37 UTC

    Searching CPAN is often a good place to start; for your specific problem the CPAN Graphics section would be a good choice.

    I know the GD module has these methods:

    • ($width,$height) = $image->getBounds()
    • $width = $image->width
    • $height = $image->height
    • $flag = $image1->compare($image2)

    There may be better choices depending on your application. For instance, if you need to do this within a GUI, Tk::Photo might be more appropriate.

    -- Ken

Re: Matching Images
by zentara (Archbishop) on Nov 22, 2010 at 12:35 UTC
    ....Is there a library ...

    The Image Magick library does it all, and it has a Perl interface.... see perl magick usage Here is a simple usage of IM, to list all pixels,.... just in case you want to test just one certain pixel. :-)

    #!/usr/bin/perl use warnings; use strict; use Image::Magick; my $file = shift or die "Need a file $!\n"; my $img = Image::Magick->new; $img->ReadImage($file); # if you want a pixel by pixel list of every color # a huge slow output $img->Set(magick => 'txt'); $img->Write("$0.txt"); ################################################## #histogram #returned values are an array of #red, green, blue, opacity, and count values. my $tot = 0; my (@colors) = $img->Histogram(); #print join "\n\n", @colors; while (1){ if (scalar @colors == 0){last} my $r = shift @colors; my $g = shift @colors; my $b = shift @colors; my $o = shift @colors; my $count = shift @colors; $tot++; print "$count ($r,$g,$b) at $o opacity\n"; } print "\n$tot total colors\n";

    I'm not really a human, but I play one on earth.
    Old Perl Programmer Haiku ................... flash japh

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://872801]
Approved by Perlbotics
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (16)
As of 2014-10-30 15:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (208 votes), past polls