#!/usr/bin/perl
use strict;
use warnings;
use Image::Magick;
die "Usage: extractor picture_name\n" if ($#ARGV == -1);
my $image = Image::Magick->new;
die "Invalid image\n" unless (0 + $image->Read($ARGV[0]));
(my $w, my $h) = $image->Get('width', 'height');
my $mask = $image->Clone();
$mask->BlackThreshold(255);
$mask->Set(type=>'Grayscale');
$mask->Draw(primitive=>'color', points=>'0,0', method=>'Floodfill', fill=>'gray(128)');
$mask->Solarize(128);
$mask->WhiteThreshold(127);
my $n = 0;
for (my $y = 0; $y < $h; $y = $y+10) {
for (my $x = 0; $x < $w; $x = $x+10) {
if (($mask->GetPixel(x=>$x, y=>$y))[0] == 0) {
my $m = $mask->Clone();
$m->Draw(primitive=>'color', points=>"$x,$y", method=>'Floodfill', fill=>'gray(128)');
$m->Solarize(128);
$m->WhiteThreshold(127);
$m->Set(type=>'Grayscale');
my $tmp1 = $image->Clone();
$tmp1->Draw(primitive=>'color', points=>"0,0", method=>'Reset', fill=>'white');
$tmp1->Composite(image=>$m, compose=>'CopyOpacity');
$tmp1->Composite(image=>$image, mask=>$m, compose=>'Copy');
$tmp1->Trim;
die "Can't save\n" unless (0 + $tmp1->Write(substr($ARGV[0], 0, -4).sprintf("%03d", $n++).".png"));
$mask->Draw(primitive=>'color', points=>"$x,$y", method=>'Floodfill', fill=>'gray(255)');
undef $m;
undef $tmp1;
};
};
};