use constant { LEFT=>0, RIGHT=>1, TOP=>2, BOTTOM=>3 }; my @bounds; for my $y ( 0 .. $height -1 ){ for my $x ( 0 .. $width - 1 ) { my $pixel = $image->pixel( $x, $y ); $bounds[ $pixel ][ LEFT ] = $x if $x < ( $bounds[ $pixel ][ LEFT ] // 1e99 ); $bounds[ $pixel ][ RIGHT ] = $x if $x > ( $bounds[ $pixel ][ RIGHT ] // 0 ); $bounds[ $pixel ][ TOP ] = $y if $y < ( $bounds[ $pixel ][ TOP ] // 1e99 ); $bounds[ $pixel ][ BOTTOM ] = $y if $y > ( $bounds[ $pixel ][ BOTTOM ] // 0 ); } }