#!/usr/local/bin/perl -w
use strict;
use Imager;

my $i = Imager->new();
$i->read(
    file => "test.jpg",
    type => "jpeg" ) or die;

print imgavg( $i,
   $i->getwidth(), $i->getheight() ), "\n";

###########################################
sub imgavg {
###########################################
  my( $i, $width, $height ) = @_;

  my $sum = 0;

  for( my $x=0; $x<$width; $x++ ) {
    for( my $y=0; $y<$height; $y++ ) {

      my $color =
        $i->getpixel( x => $x, y => $y );

      my ($red, $green, $blue, $alpha) =
        $color->rgba();

      $sum +=
        ( $red + $green + $blue ) / 3;
    }
  }

  return int( $sum / $width / $height );
}