#!/usr/bin/perl -w

my $COPY = <<'EOC';

  Copyright (c) 2005 Stuart Prescott    perl@nanonanonano.net
  Released under the GNU General Public Licence.

EOC

use strict;
use Image::Magick;

my $filename = $ARGV[0];
if (! defined $filename || $filename eq '' || ! -f $filename) {
  print "Please specify a file to analyse\n";
  exit -1;
}
my $outputFile = $filename.'-threshold.png';

my $cmax = 65535;
my ($rtl, $gtl, $btl) = ($cmax * 0,   $cmax * 0,   $cmax * 0.8);
my ($rtu, $gtu, $btu) = ($cmax * 0.2, $cmax * 0.9, $cmax);

my($image, $x);

$image = Image::Magick->new;
$x = $image->Read($filename);
warn "$x" if "$x";

my $height = $image->Get("height");
my $width  = $image->Get("width");

my $output = Image::Magick->new;
$output->Set(size=>"${width}x$height");
$output->ReadImage('xc:white');

my $area=0;
my $imgarea = $height * $width;
for (my $x=1; $x<=$width; $x++) {
  for (my $y=1; $y<=$height; $y++) {
    my $colour = $image->Get("pixel[$x,$y]");
    my ($r, $g, $b, @junk) = split(/,/, $colour);
    #print "Got: $r, $g, $b\n";
    if ($r >= $rtl && $g >= $gtl && $b >= $btl
     && $r <= $rtu && $g <= $gtu && $b <= $btu) {
      $area++;
      $output->Set("pixel[$x,$y]" => 'black');
    }
  }
}
print "Analysis of image $filename (${height}x$width)\n";
print "Number of pixels analysed:\t".$imgarea."\n";
print "Number of pixels above threshold:\t".$area."\n";
print "Percentage area above threshold:\t".($area/$imgarea*100)."\n";
print "Percentage area below threshold:\t".(100-$area/$imgarea*100)."\n";
$output->Write("png:$outputFile");
system "kuickshow '$outputFile' &";
